
# import enum

import requests

# from django.contrib import messages
# from django.db.models import F, Max, Q, Sum
from django.http.response import JsonResponse

# from django.shortcuts import get_object_or_404, redirect, render
from django.shortcuts import redirect, render

# from django.urls import reverse
# from django.utils import timezone
from django.views.decorators.http import require_http_methods

import db
# import re
from .forms import SignUpForm  # NaryadFullForm, PatientForm,
from .models import (
    Spr_dlj,
    Spr_lpu,
    Spr_otd,
    Spr_sdl,
    Spr_worker,
    Spr_worker_dlj,
)


def index(request):
    print("")
    # return render(request, "naryad/load_image.html")


def once_spr_otd():
    select_otdfr = db.sel_dict_in_list_lowerkeys("select otd,notd,lpu,gr_otd,notd_kr from np_otd")
    for z in select_otdfr:
        lput = Spr_lpu.objects.filter(lpu=z["lpu"]).first()
        if lput is not None:
            Spr_otd.objects.create(
                otd=z["otd"], name_otd=z["notd"], lpu=lput, name_otdkr=z["notd_kr"], type_otd=z["gr_otd"],
            )
    print(select_otdfr)
    # return JsonResponse({"once_spr_otd": select_otdfr})


def once_spr_dlj():
    select_dljfr = db.sel_dict_in_list_lowerkeys("select dlj,ndlj from n_dlj where tv=1 order by dlj")
    for z in select_dljfr:
        # lput = Spr_lpu.objects.filter(lpu=z["lpu"]).first()
        # if lput is not None:
        Spr_dlj.objects.create(dlj=z["dlj"], name_dlj=z["ndlj"])
    print(select_dljfr)
    # return JsonResponse({"once_spr_dlj": select_dljfr})


def once_spr_worker():
    select_workerfr = db.sel_dict_in_list_lowerkeys(
        "select mpp,fam,im,ot,dip,snl,tel from n_mpp where pv=1 and im<>'' order by mpp",
    )
    for z in select_workerfr:
        # lput = Spr_lpu.objects.filter(lpu=z["lpu"]).first()
        # if lput is not None:
        dip = z["dip"]
        if dip is None:
            dip = ""
        snl = z["snl"]
        if snl is None:
            snl = ""
        tel = z["tel"]
        if tel is None:
            tel = ""
        Spr_worker.objects.create(
            mpp=z["mpp"], fam=z["fam"], im=z["im"], ot=z["ot"], diplom=dip, snils=snl, telephone=tel,
        )
    print(select_workerfr)
    # return JsonResponse({"once_spr_worker": select_workerfr})


def once_spr_workerdlj():
    select_workerfr = db.sel_dict_in_list_lowerkeys(
        "select doc,mpp,otd,pr_dlj,sdl,dolj,lpu,vid_priema,doc_exp from n_doc where mpp in (select mpp from n_mpp where pv=1 and im<>'')",
    )
    for z in select_workerfr:
        id_w = Spr_worker.objects.filter(mpp=z["mpp"]).first()
        id_d = Spr_dlj.objects.filter(dlj=z["dolj"]).first()
        lput = Spr_lpu.objects.filter(lpu=z["lpu"]).first()
        id_o = Spr_otd.objects.filter(otd=z["otd"]).first()
        id_s = Spr_sdl.objects.filter(sdl=z["sdl"]).first()
        Spr_worker_dlj.objects.create(
            id_worker=id_w,
            doc=z["doc"],
            id_dlj=id_d,
            id_lpu=lput,
            id_otd=id_o,
            id_sdl=id_s,
            work_tip=z["pr_dlj"],
            stavka=1,
            doc_exp=z["doc_exp"],
            vid_priema=z["vid_priema"],
        )
    print(select_workerfr)
    # return JsonResponse({"once_spr_worker": select_workerfr})


# @require_http_methods(["GET", "POST"])
# def someview(request) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse:
#     if request.method == "POST" or request.method == "FILES":
#         form = NaryadFullForm(request.POST or None, request.FILES or None)
#         files = request.FILES.getlist("images")
#         if form.is_valid():
#             naryad = It_lab(
#                 patient=form.cleaned_data["patient"],
#                 idkv=form.cleaned_data["idkv"],
#                 nkv=form.cleaned_data["nkv"],
#                 dou=form.cleaned_data["dou"],
#                 dzr=form.cleaned_data["dzr"],
#                 stu=form.cleaned_data["stu"],
#                 opl=form.cleaned_data["opl"],
#                 sris=form.cleaned_data["sris"],
#                 id_etap=form.cleaned_data["id_etap"],
#                 dnaz_etap=form.cleaned_data["dnaz_etap"],
#                 dn_etap=form.cleaned_data["dn_etap"],
#                 dz_etap=form.cleaned_data["dz_etap"],
#                 user_etap=form.cleaned_data["user_etap"],
#                 mpp_etap=form.cleaned_data["mpp_etap"],
#                 sdl_etap=form.cleaned_data["sdl_etap"],
#                 kom_etap=form.cleaned_data["kom_etap"],
#             )
#             naryad.save()
#             for f in files:
#                 Images.objects.create(etap=naryad, img=f)
#             return redirect("/naryad_list")
#     else:
#         form = NaryadFullForm()
#     return render(request, "naryad/create_naryad.html", {"form": form})


# @require_http_methods(["GET", "POST"])
# def updateview(request, pk: int) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse:
#     if request.method == "POST":
#         naryad = It_lab.objects.get(pk=pk)
#         tech_mpp = request.POST.get("select_tech")
#         lit_mpp = request.POST.get("select_lit")
#         pol_mpp = request.POST.get("select_pol")
#         cadcam_mpp = request.POST.get("select_cadcam")
#         sdl_set = naryad.sdl_set
#         prev_etap_spec = request.POST.get("prevEtapSwitchCheck")

#         if sdl_set.tech != tech_mpp:
#             sdl_set.tech = tech_mpp
#         if sdl_set.lit != lit_mpp:
#             sdl_set.lit = lit_mpp
#         if sdl_set.cadcam != cadcam_mpp:
#             sdl_set.cadcam = cadcam_mpp
#         if sdl_set.pol != pol_mpp:
#             sdl_set.pol = pol_mpp
#         sdl_set.save()

#         if prev_etap_spec:
#             etaps = It_lab.objects.filter(idkv=naryad.idkv)
#             for etap in etaps:
#                 match etap.sdl_etap.sdl:
#                     case 1:
#                         etap.mpp_etap = sdl_set.doc
#                         etap.save()
#                     case 35:
#                         etap.mpp_etap = tech_mpp
#                         etap.save()
#                     case 36:
#                         etap.mpp_etap = pol_mpp
#                         etap.save()
#                     case 37:
#                         etap.mpp_etap = lit_mpp
#                         etap.save()
#                     case 38:
#                         etap.mpp_etap = cadcam_mpp
#                         etap.save()

#         if request.POST.get("kom_etap") != naryad.kom_etap:
#             naryad.kom_etap = request.POST.get("kom_etap")
#             naryad.save()

#         if request.POST.get("btn_next") == "nextEtap":
#             if naryad.sdl_etap.sdl in [1, 36, 37, 38] or naryad.id_etap == 1:
#                 return redirect("/naryad/next_etap/" + str(naryad.id) + "/" + "35" + "/" + "false")
#             else:
#                 return redirect("/naryad/naryad_upd/" + str(naryad.id))
#         else:
#             return redirect("/naryad/naryad_upd/" + str(naryad.id))

#     else:
#         etap_queryset = (
#             It_lab.objects.filter(pk=pk)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         etap = etap_queryset[0]
#         idkv = etap.idkv
#         previous_etap = (
#             It_lab.objects.filter(idkv=idkv, dz_etap__isnull=False)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#             .order_by("-id_etap")
#         )

#         list_tech = User_sdl.objects.filter(access__access="tech")

#         list_lit = User_sdl.objects.filter(access__access="lit")

#         list_cadcam = User_sdl.objects.filter(access__access="cad")

#         list_pol = User_sdl.objects.filter(access__access="pol")

#         dolzh = User_sdl.objects.get(user=request.user).access_list()
#         return render(
#             request,
#             "naryad/update_naryad.html",
#             {
#                 "previous_etap": previous_etap,
#                 "etap": etap,
#                 "tech_list": list_tech,
#                 "lit_list": list_lit,
#                 "cadcam_list": list_cadcam,
#                 "pol_list": list_pol,
#                 "dolzh": dolzh,
#             },
#         )


# @require_http_methods(["GET"])
# def next_etap(
#     request, id: int, sdl: int, nuxt="False", mpp=0, container=0
# ) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
#     naryad = It_lab.objects.get(pk=id)
#     if naryad.id_etap == 0 and container == 0:
#         return redirect("/naryad/naryad_list")
#     if It_lab.objects.filter(idkv=naryad.idkv, id_etap=naryad.id_etap + 1).exists():
#         if nuxt == "True":
#             return JsonResponse({"status": "exist"})
#         return redirect("/naryad/naryad_list")
#     else:
#         user_etap_link = None
#         naryad.dz_etap = datetime.date.today().strftime("%Y-%m-%d")
#         if nuxt == "True":
#             if naryad.id_etap == 1:
#                 st_etap = MyUser.objects.get(mpp=mpp)
#                 naryad.user_etap_link = st_etap
#                 naryad.mpp_etap = st_etap.mpp
#                 naryad.user_etap = st_etap.login
#                 sdl_setnew = naryad.sdl_set
#                 sdl_setnew.tech_st = st_etap.mpp
#                 sdl_setnew.save()
#         if naryad.id_etap == 0:
#             sdl_etap = Spr_sdl.objects.get(sdl=3500)
#             user_etap_link = None
#         elif naryad.id_etap == 1:
#             sdl_etap = Spr_sdl.objects.get(sdl=sdl)
#             user_etap_link = MyUser.objects.get(mpp=mpp)
#         else:
#             if sdl == 3500:
#                 sdl = 35
#             sdl_etap = Spr_sdl.objects.get(sdl=sdl)
#             user_etap_link = MyUser.objects.get(mpp=mpp)
#         next_mpp = 0
#         user_etap = ""
#         match sdl:
#             case 1:
#                 next_mpp = naryad.sdl_set.doc
#                 next_user = MyUser.objects.get(mpp=next_mpp)
#                 user_etap_link = next_user
#                 user_etap = next_user.login
#             case 35:
#                 if naryad.id_etap == 0:
#                     user_etap_link = None
#                     user_etap = ""
#                 else:
#                     next_mpp = naryad.sdl_set.tech
#                     next_user = MyUser.objects.get(mpp=next_mpp)
#                     user_etap_link = next_user
#                     user_etap = next_user.login
#             case 36:
#                 next_mpp = naryad.sdl_set.pol
#                 next_user = MyUser.objects.get(mpp=next_mpp)
#                 user_etap_link = next_user
#                 user_etap = next_user.login
#             case 37:
#                 next_mpp = naryad.sdl_set.lit
#                 next_user = MyUser.objects.get(mpp=next_mpp)
#                 user_etap_link = next_user
#                 user_etap = next_user.login
#             case 38:
#                 next_mpp = naryad.sdl_set.cadcam
#                 next_user = MyUser.objects.get(mpp=next_mpp)
#                 user_etap_link = next_user
#                 user_etap = next_user.login
#         if naryad.container.id > 0:
#             container_used = naryad.container
#             if container_used.used is False:
#                 container_used.used = True
#                 container_used.nkv = naryad.nkv
#                 container_used.save()
#         elif naryad.container.id == 0 and container > 0:
#             container_used = Container.objects.get(id=container)
#             container_used.used = True
#             container_used.nkv = naryad.nkv
#             container_used.save()
#             naryad.container = container_used
#         else:
#             container_used = Container.objects.get(id=0)
#             container_used.save()
#             naryad.container = container_used
#         naryad.save()
#         naryad_next_etap = It_lab(
#             patient=naryad.patient,
#             idkv=naryad.idkv,
#             nkv=naryad.nkv,
#             dou=naryad.dou,
#             dzr=None,
#             stu=naryad.stu,
#             opl=naryad.opl,
#             sris=naryad.sris,
#             id_etap=naryad.id_etap + 1,
#             dnaz_etap=datetime.date.today().strftime("%Y-%m-%d"),
#             dn_etap=datetime.date.today().strftime("%Y-%m-%d"),
#             dz_etap=None,
#             user_etap=user_etap,
#             mpp_etap=next_mpp,
#             sdl_etap=sdl_etap,
#             lpu=naryad.lpu,
#             kom_etap="",
#             sdl_set=naryad.sdl_set,
#             naryad_doc=naryad.naryad_doc,
#             user_etap_link=user_etap_link,
#             id_last=naryad.id_last,
#             container=container_used,
#         )
#         naryad_next_etap.save()
#         s = naryad_next_etap.id_last
#         s.number = naryad_next_etap.id
#         s.save()
#         if nuxt == "True":
#             return JsonResponse({"status": "ok"})
#         return redirect("/naryad/naryad_list")


# class Naryad_to_list:
#     def __init__(self, naryad: It_lab) -> dict:
#         return {
#             "dou": naryad.dou,
#             "dzr": naryad.dzr,
#             "pdr": naryad.pdr,
#             "nkv": naryad.nkv,
#             "stu": naryad.stu,
#             "idkv": naryad.idkv,
#             "patient__fam": naryad.patient.fam,
#             "patient__im": naryad.patient.im,
#             "patient__ot": naryad.patient.ot,
#             "sdl_set__doc": naryad.sdl_set.doc,
#         }


# @require_http_methods(["GET"])
# def pdr_naryad(request, pk: int, usl: int = 0) -> JsonResponse:
#     naryad = It_lab.objects.get(pk=pk)
#     mpp = naryad.sdl_set.doc
#     opl = naryad.opl
#     month = datetime.now().month
#     year = datetime.now().year

#     try:
#         if Zav_pdr.objects.filter(mpp=mpp, year=year, month=month, opl=opl).exists():
#             zav_pdr = Zav_pdr.objects.get(mpp=mpp, year=year, month=month, opl=opl)
#             naryad_log_text = f"{naryad.nkv}-{datetime.now().date()}-{naryad.opl}-{naryad.stu}"
#             log = zav_pdr.log + ";" + "AddPdrNar" + naryad_log_text
#             if usl:
#                 kol_usl = zav_pdr.kol_usl + 1
#                 kol_all = zav_pdr.kol_all + 1
#                 stu_usl = zav_pdr.stu_usl + naryad.stu
#                 stu_all = zav_pdr.stu_all + naryad.stu
#                 nars_usl = []
#                 nars_usl.append(zav_pdr.nars_usl)
#                 nars_usl.append(Naryad_to_list(naryad))
#                 Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).update(
#                     kol_usl=kol_usl,
#                     kol_all=kol_all,
#                     stu_usl=stu_usl,
#                     stu_all=stu_all,
#                     nars_usl=nars_usl,
#                     log=log,
#                 )
#             else:
#                 kol_lab = zav_pdr.kol_lab + 1
#                 kol_all = zav_pdr.kol_all + 1
#                 stu_lab = zav_pdr.stu_lab + naryad.stu
#                 stu_all = zav_pdr.stu_all + naryad.stu
#                 nars_lab = (zav_pdr.nars_lab).append(Naryad_to_list(naryad))
#                 Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).update(
#                     kol_lab=kol_lab,
#                     kol_all=kol_all,
#                     stu_lab=stu_lab,
#                     stu_all=stu_all,
#                     nars_lab=nars_lab,
#                     log=log,
#                 )
#         else:
#             if usl:
#                 Zav_report.objects.create(
#                     mpp=mpp,
#                     year=year,
#                     month=month,
#                     opl=opl,
#                     kol_usl=kol_usl,
#                     kol_all=kol_all,
#                     stu_usl=stu_usl,
#                     stu_all=stu_all,
#                     nars_usl=nars_usl,
#                 )
#             else:
#                 Zav_report.objects.create(
#                     mpp=mpp,
#                     year=year,
#                     month=month,
#                     opl=opl,
#                     kol_lab=kol_lab,
#                     kol_all=kol_all,
#                     stu_lab=stu_lab,
#                     stu_all=stu_all,
#                     nars_lab=nars_lab,
#                 )
#         return JsonResponse({"status": "ok"})
#     except Exception as error_message:
#         return JsonResponse({"ststus": "error", "error_message": f"{error_message}"})


# @require_http_methods(["GET"])
# def finish_naryad(request, pk: int, nuxt=False) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
#     naryad = It_lab.objects.get(pk=pk)
#     naryad.dz_etap = datetime.date.today().strftime("%Y-%m-%d")
#     naryad.save()
#     dzr = datetime.date.today().strftime("%Y-%m-%d")
#     It_lab.objects.filter(idkv=naryad.idkv).update(pdzr=dzr)
#     if naryad.container.id > 0:
#         try:
#             cont = Container.objects.get(id=naryad.container.id)
#             cont_nar = It_lab.objects.filter(container=cont)
#             if len(cont_nar) > 0:
#                 cont.nkv = cont_nar[0].nkv
#                 cont.save()
#             else:
#                 Container.objects.filter(id=naryad.container.id).update(used=False, nkv=0)
#         except Exception as error:
#             print(error)
#     try:
#         idkv = naryad.idkv
#         dzr = dzr
#         uid = naryad.patient.uid
#         dou = naryad.dou
#         nom_teh = naryad.sdl_set.tech
#         nom_lit = naryad.sdl_set.lit
#         nom_pol = naryad.sdl_set.pol
#         nom_cadcam = naryad.sdl_set.cadcam
#         dou = naryad.dou
#         dou = f"'{dou}'"
#         dzr = datetime.date.today().strftime("%d.%m.%Y")
#         dzr = f"'{dzr}'"
#         check_zn = db.select(sql.SLQ_LAB_SEL_ISP.format(idkv=idkv))
#         if check_zn == []:
#             db.write(
#                 sql.SQL_LAB_INS_ISP.format(
#                     idkv=idkv, nom_teh=nom_teh, nom_lit=nom_lit, nom_pol=nom_pol, nom_var="0", dzr=dzr
#                 )
#             )
#         else:
#             db.write(
#                 sql.SQL_LAB_UPD_ISP.format(
#                     idkv=idkv, nom_teh=nom_teh, nom_lit=nom_lit, nom_pol=nom_pol, nom_var="0", dzr=dzr
#                 )
#             )

#         check_teh = db.select(sql.SLQ_LAB_CHK_TEH.format(idkv=idkv))
#         idus = db.select(sql.SLQ_LAB_IDUS.format(idkv=idkv))[0][0]
#         if check_teh == []:
#             idbr = db.proc("NEW_PL_IDBR")[0]
#         else:
#             idbr = check_teh[0][0]
#         # Если есть техник, создать данные в таблице бригад
#         if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh)) != []:
#             doc_teh = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh))[0][0] or 0

#             db.write(
#                 sql.SLQ_LAB_UPD_TEH.format(
#                     uid=uid, idus=idus, nom_teh=nom_teh, idkv=idkv, dou=dou, idbr=idbr, doc=doc_teh
#                 )
#             )

#         check_pol = db.select(sql.SLQ_LAB_CHK_POL.format(idkv=idkv))
#         if check_pol == []:
#             idbr = db.proc("NEW_PL_IDBR")[0]
#         else:
#             idbr = check_pol[0][0]
#         if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol)) != []:
#             doc_pol = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol))[0][0] or 0
#             db.write(
#                 sql.SLQ_LAB_UPD_POL.format(
#                     uid=uid, idus=idus, nom_pol=nom_pol, idkv=idkv, dou=dou, idbr=idbr, doc=doc_pol
#                 )
#             )

#         check_lit = db.select(sql.SLQ_LAB_CHK_LIT.format(idkv=idkv))
#         if check_lit == []:
#             idbr = db.proc("NEW_PL_IDBR")[0]
#         else:
#             idbr = check_lit[0][0]
#         if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit)) != []:
#             doc_lit = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit))[0][0] or 0
#             db.write(
#                 sql.SLQ_LAB_UPD_LIT.format(
#                     uid=uid, idus=idus, nom_lit=nom_lit, idkv=idkv, dou=dou, idbr=idbr, doc=doc_lit
#                 )
#             )

#         check_cadcam = db.select(sql.SLQ_LAB_CHK_CADCAM.format(idkv=idkv))
#         if check_cadcam == []:
#             idbr = db.proc("NEW_PL_IDBR")[0]
#         else:
#             idbr = check_cadcam[0][0]
#         if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam)) != []:
#             doc_cadcam = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam))[0][0] or 0
#             db.write(
#                 sql.SLQ_LAB_UPD_CADCAM.format(
#                     uid=uid, idus=idus, nom_cadcam=nom_cadcam, idkv=idkv, dou=dou, idbr=idbr, doc=doc_cadcam
#                 )
#             )

#         # если дата формата дд.мм.гг то запись на отправку---------------------------------
#         s = db.select(f"select dzr, status, pdog from pl_uslk where idkv={idkv}")
#         if s != []:
#             if s[0][0] is None:
#                 db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=5, dzr=dzr))
#                 # send_telegram(f"Установлен dzr для наряда: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}")
#         else:
#             db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=5, dzr=dzr))
#             # send_telegram(f"Успешно создано закрытие наряда idkv: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}")
#     except Exception as exerr:
#         send_telegram(f"Наряд idkv: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}, ошибка{exerr}")
#     if nuxt in ("True", True):
#         return JsonResponse({"status": "ok"})
#     return redirect("/naryad/naryad_list")


def send_telegram(text: str):
    token = "6259020847:AAHdMHEmhQ8fJ4EU-lRdVZowxp8aTTZaJW4"
    chat_id = "-1001893335420"
    url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + text
    # results = requests.get(url_req)
    requests.get(url_req)

    # if results.status_code != 200:
    # logger.warning("post_text error")
    # raise Exception("post_text error")


# class NaryadFullFormList(ListView):
#     model = It_lab
#     form_class = NaryadFullForm
#     template_name = "naryad/list_naryad.html"

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context["naryad_list"] = (
#             It_lab.objects.exclude(id_etap=1)
#             .filter(dz_etap__isnull=True)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         return context


# @method_decorator(require_http_methods(["GET", "POST"]), name="dispatch")
# class NaryadFullFormListSt(ListView):
#     model = It_lab
#     form_class = NaryadFullForm
#     template_name = "naryad/list_naryad.html"

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context["naryad_list"] = (
#             It_lab.objects.filter(dz_etap__isnull=True, id_etap=1)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )

#         return context


# @require_http_methods(["GET"])
# def naryad_list(request) -> HttpResponse:
#     user = request.user
#     # if any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["tech_st", "prog"]):
#     if any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["prog"]):
#         naryad_list = (
#             It_lab.objects.filter(dz_etap__isnull=True)
#             .order_by("dn_etap")
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         naryad_wait_count = naryad_list.count()

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()

#     elif any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["tech_st"]):
#         naryad_list = (
#             It_lab.objects.filter(Q(id_etap=1) | Q(mpp_etap=user.mpp), Q(dz_etap__isnull=True))
#             .order_by("-dn_etap")
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         # naryad_wait_count = It_lab.objects.filter(Q(id_etap=1) | Q(mpp_etap=user.mpp), dz_etap__isnull=True).count()
#         # naryad_wait_count = naryad_list.count()
#         naryad_wait_count = It_lab.objects.filter(Q(id_etap=1) | Q(mpp_etap=user.mpp), dz_etap__isnull=True).count()

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True, id_etap__gt=1).distinct("idkv").count()

#         # naryad_list = naryad_list.order_by("idkv", "id_etap").distinct("idkv")
#         # naryad_list = naryad_list.order_by("idkv", "id_etap").distinct("idkv")
#         # naryad_list = naryad_list.filter(id_etap__gt=0)
#     else:
#         # sdls_list = User_sdl.objects.get(user=user).sdl_list()

#         naryad_list = (
#             It_lab.objects.select_related("patient")
#             .prefetch_related("images")
#             .filter(dz_etap__isnull=True, mpp_etap=user.mpp)
#             .order_by("dn_etap")
#         )
#         naryad_wait_count = naryad_list.count()

#         naryad_in_work_count = (
#             It_lab.objects.filter(dz_etap__isnull=False).exclude(mpp_etap=user.mpp).distinct("idkv").count()
#         )

#     return render(
#         request,
#         "naryad/list_naryad.html",
#         {
#             "naryad_list": naryad_list,
#             "naryad_wait_count": naryad_wait_count,
#             "naryad_in_work_count": naryad_in_work_count,
#         },
#     )


# @require_http_methods(["GET"])
# def naryad_list_finish(request) -> HttpResponse:
#     user = request.user
#     if any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["tech_st"]):
#         naryad_list = (
#             It_lab.objects.filter(dzr__isnull=False)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .order_by("idkv", "id_etap")
#             .distinct("idkv")
#         )

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True).filter(id_etap__gt=0).count()

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()

#     elif any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["prog"]):
#         naryad_list = (
#             It_lab.objects.select_related("patient")
#             .prefetch_related("images")
#             .filter(dzr__isnull=False)
#             .order_by("idkv", "id_etap")
#             .distinct("idkv")
#         )

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True).filter().count()

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()

#     else:
#         naryad_list = (
#             It_lab.objects.select_related("patient")
#             .prefetch_related("images")
#             .filter(dz_etap__isnull=False, mpp_etap=user.mpp)
#             .exclude()
#             .order_by()
#             .distinct("idkv")
#         )

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True, mpp_etap=user.mpp).count()

#         naryad_in_work_count = (
#             It_lab.objects.filter(dz_etap__isnull=False).exclude(mpp_etap=user.mpp).distinct("idkv").count()
#         )

#     return render(
#         request,
#         "naryad/list_naryad_done.html",
#         {
#             "naryad_list": naryad_list,
#             "naryad_wait_count": naryad_wait_count,
#             "naryad_in_work_count": naryad_in_work_count,
#         },
#     )


# @require_http_methods(["GET"])
# def naryad_list_in_work(request) -> HttpResponse:
#     user = request.user
#     if any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["tech_st"]):
#         naryad_list = (
#             It_lab.objects.select_related("patient")
#             .prefetch_related("images")
#             .filter(dz_etap__isnull=True, id_etap__gt=1)
#             .order_by()
#             .distinct("idkv")
#         )

#         naryad_wait_count = It_lab.objects.filter(Q(id_etap=1) | Q(mpp_etap=user.mpp), dz_etap__isnull=True).count()

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True, id_etap__gt=1).distinct("idkv").count()

#     elif any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["prog"]):
#         naryad_list = (
#             It_lab.objects.select_related("patient")
#             .prefetch_related("images")
#             .filter(dz_etap__isnull=True)
#             .order_by("idkv", "id_etap")
#             .distinct("idkv")
#         )

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True).count()

#     else:
#         naryad_list = (
#             It_lab.objects.filter(dz_etap__isnull=False, dzr__isnull=True)
#             .exclude(mpp_etap=user.mpp)
#             .order_by("idkv")
#             .distinct("idkv")
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#         )

#         naryad_in_work_count = (
#             It_lab.objects.filter(dz_etap__isnull=False).exclude(mpp_etap=user.mpp).distinct("idkv").count()
#         )

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True, mpp_etap=user.mpp).distinct("idkv").count()

#     return render(
#         request,
#         "naryad/list_naryad_in_work.html",
#         {
#             "naryad_list": naryad_list,
#             "naryad_wait_count": naryad_wait_count,
#             "naryad_in_work_count": naryad_in_work_count,
#         },
#     )


# @require_http_methods(["GET"])
# def naryad_list_st(request) -> HttpResponse:
#     naryad_list = (
#         It_lab.objects.filter(dz_etap__isnull=True, id_etap=1)
#         .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#         .prefetch_related("images")
#         .all()
#     )
#     tech_list = Spr_kadr_tech.objects.all()
#     pol_list = Spr_kadr_pol.objects.all()
#     lit_list = Spr_kadr_lit.objects.all()
#     cadcam_list = Spr_kadr_cadcam.objects.all()
#     doc_list = Spr_kadr_tech.objects.all()

#     return render(
#         request,
#         "naryad/list_naryad_st.html",
#         {
#             "naryad_list": naryad_list,
#             "tech_list": tech_list,
#             "pol_list": pol_list,
#             "lit_list": lit_list,
#             "cadcam_list": cadcam_list,
#             "doc_list": doc_list,
#         },
#     )


# @require_http_methods(["GET"])
# def set_sdl_naryad(request, id: int) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
#     naryad = It_lab.objects.get(pk=id)
#     tech = request.POST.get("tech")
#     lit = request.POST.get("lit")
#     pol = request.POST.get("pol")
#     cadcam = request.POST.get("cadcam")
#     sdl_set_new = naryad.sdl_set

#     if tech:
#         sdl_set_new.tech = tech
#     if lit:
#         sdl_set_new.lit = lit
#     if pol:
#         sdl_set_new.pol = pol
#     if cadcam:
#         sdl_set_new.cadcam = cadcam
#     sdl_set_new.save()
#     naryad.sdl_set = sdl_set_new
#     naryad.save()
#     return redirect("/naryad_list")


# @method_decorator(require_http_methods(["GET", "POST"]), name="dispatch")
# class PatientCreateView(CreateView):
#     model = Patient
#     form_class = PatientForm
#     template_name = "naryad/create_patient.html"
#     success_url = "naryad_add"


# @method_decorator(require_http_methods(["GET", "POST"]), name="dispatch")
# class PatientUpdateView(UpdateView):
#     model = Patient
#     fields = "__all__"
#     template_name = "naryad/create_patient.html"
#     success_url = "/naryad/done"

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context["patient"] = Patient.objects.all()
#         return context


# @method_decorator(require_http_methods(["GET", "POST"]), name="dispatch")
# class PatientListView(ListView):
#     model = Patient
#     fields = "__all__"
#     template_name = "naryad/create_patient.html"
#     success_url = "/naryad/done"

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context["patient"] = Patient.objects.all()
#         return context


# @method_decorator(require_http_methods(["GET", "POST"]), name="dispatch")
# class ImageCreateView(CreateView):
#     model = Images
#     fields = "__all__"
#     template_name = "naryad/create_image.html"
#     success_url = "/naryad/done"

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context["patient"] = Patient.objects.all()
#         return context


# @require_http_methods(["POST"])
# def image_add(request) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
#     # if request.method == "POST":
#     file = request.FILES.get("image")
#     etap_id = request.POST.get("etap_id")
#     etap = It_lab.objects.get(pk=etap_id)
#     Images.objects.create(etap=etap, img=file, naryad=etap.nkv)
#     if request.POST.get("nuxt") == "true":
#         return JsonResponse({"status": "ok"})
#     str_redir = "/naryad/naryad_upd/" + str(etap_id)
#     return redirect(str_redir)


# @require_http_methods(["GET"])
# def image_list(request, nkv) -> HttpResponse:
#     image_list = Images.objects.filter(naryad=nkv).all().order_by("-id")
#     image_urls = [x.img.url for x in image_list]
#     if len(image_urls) > 0:
#         return JsonResponse({"status": "ok", "image_list": image_urls})
#     return JsonResponse({"status": "no_images"})


# @require_http_methods(["GET"])
# def image_fullscreen(request, pk) -> HttpResponse:
#     image = Images.objects.get(pk=pk)
#     return render(request, "naryad/image_fullscreen.html", {"image": image})


# @require_http_methods(["GET"])
# def delete_img(request, source, pk_naryad, pk_image) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
#     if source == "upd":
#         Images.objects.get(pk=pk_image).delete()
#         return redirect("/naryad/naryad_upd/" + str(pk_naryad))
#     elif source == "list":
#         return redirect("/naryad/naryad_list")
#     else:
#         return redirect("/naryad/naryad_list")


# @require_http_methods(["GET"])
# def naryad_report(request) -> HttpResponse:
#     user = request.user
#     if any(elem in User_sdl.objects.get(user=user).access_list() for elem in ["tech_st", "prog", "zav_ort"]):
#         etaps_in_work = (
#             It_lab.objects.filter(dz_etap__isnull=True)
#             .exclude(id_etap__lt=3)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         naryads_in_work = etaps_in_work.order_by().distinct("idkv")
#         naryad_list_done = (
#             It_lab.objects.filter(dz_etap__isnull=False, id_etap__gt=1)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         naryad_list_done_dist = naryad_list_done.order_by().distinct("idkv")

#         naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True, mpp_etap=user.mpp).count()

#     else:
#         etaps_in_work = (
#             It_lab.objects.filter(dz_etap__isnull=True, mpp_etap=user.mpp)
#             .exclude(id_etap__lt=3)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         naryads_in_work = etaps_in_work.order_by().distinct("idkv")
#         naryad_list_done = (
#             It_lab.objects.filter(dz_etap__isnull=False, id_etap__gt=1, mpp_etap=user.mpp)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .prefetch_related("images")
#             .all()
#         )
#         naryad_list_done_dist = naryad_list_done.order_by().distinct("idkv")

#         naryad_in_work_count = (
#             It_lab.objects.filter(dz_etap__isnull=False).exclude(mpp_etap=user.mpp).distinct("idkv").count()
#         )

#         naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True, mpp_etap=user.mpp).count()

#     summ_nar = 0.0
#     for nar in naryad_list_done:
#         summ_nar += nar.stu
#     # done_nar_list = [x for x in naryad_list_done if x.dzr not in [None, ""]]
#     naryad_list = It_lab.objects.all()
#     return render(
#         request,
#         "naryad/report.html",
#         {
#             "count_done_nar": len(naryad_list_done_dist),
#             "count_inwork_nar": len(naryads_in_work),
#             "inwork_nar_list_unice": len(naryads_in_work),
#             "naryad_list": naryad_list,
#             "naryad_list_done": naryad_list_done,
#             "naryads_in_work": len(naryads_in_work),
#             "user": user,
#             "sum_inwork_nar": len(naryads_in_work),
#             "sum_done_nar": summ_nar,
#             "naryad_in_work_count": naryad_in_work_count,
#             "naryad_wait_count": naryad_wait_count,
#         },
#     )


sql_uslugi_load = """select pl_uslp.kusl,n_usl.nusl,pl_uslp.kol,pl_uslp.price,pl_uslp.stu
from pl_uslp, n_usl
where pl_uslp.usl=n_usl.usl
 and pl_uslp.idkv='{idkv}'"""


# @require_http_methods(["GET"])
# def uslugi_modal(request, pk) -> HttpResponse:
#     naryad = It_lab.objects.get(pk=pk)
#     uslugi = firebird_db.sel_dict_in_list_desc(sql_uslugi_load.format(idkv=naryad.idkv))
#     summa = math.fsum([float(usl["STU"]) for usl in uslugi])
#     return render(request, "naryad/modal_uslugi.html", {"uslugi": uslugi, "naryad": naryad, "summa": summa})


# @require_http_methods(["POST"])
# @csrf_exempt
# def naryad_to_lab(request):
#     json_data = request.body
#     naryad = json.loads(json_data)
#     # pp = pprint.PrettyPrinter(width=100)

#     if It_lab.objects.filter(idkv=naryad["idkv"], id_etap=naryad["id_etap"]).exists():
#         uslugi = naryad.pop("uslugi")
#         for usl in uslugi:
#             if Pl_uslp.objects.filter(idkv=naryad["idkv"], usl=usl["usl"]).exists():
#                 Pl_uslp.objects.filter(idkv=naryad["idkv"], usl=usl["usl"]).delete()
#                 usl = Pl_uslp.objects.create(idkv=naryad["idkv"], **usl)
#         cost = naryad.pop("stu")
#         try:
#             It_lab.objects.filter(idkv=naryad["idkv"]).update(stu=cost)
#         except Exception as errexc:
#             print(errexc)
#             pass
#         # for one in naryads:
#         #     one.stu = cost
#         #     one.save()
#         #     naryads = It_lab.objects.filter(idkv=naryad["idkv"])
#         #     for one in naryads:
#         #         one.usl
#         # else:
#         return JsonResponse({"status": "ok", "message": "Наряд успешно загружен", "idkv": naryad["idkv"]}, status=200)

#     else:
#         lpu_data = naryad.pop("lpu")
#         if Spr_lpu.objects.filter(lpu=lpu_data["lpu"]).exists():
#             lpu = Spr_lpu.objects.get(lpu=lpu_data["lpu"])
#         else:
#             lpu = Spr_lpu.objects.create(**lpu_data)

#         patient_data = naryad.pop("patient")
#         if Patient.objects.filter(uid=patient_data["uid"]).exists():
#             patient = Patient.objects.get(uid=patient_data["uid"])
#         else:
#             patient = Patient.objects.create(**patient_data)

#         opl_data = naryad.pop("opl")
#         if Spr_opl.objects.filter(opl=opl_data["opl"]).exists():
#             opl = Spr_opl.objects.get(opl=opl_data["opl"])
#         else:
#             opl = Spr_opl.objects.create(**opl_data)

#         sdl_etap_data = naryad.pop("sdl_etap")
#         if Spr_sdl.objects.filter(sdl=sdl_etap_data["sdl"]).exists():
#             sdl_etap = Spr_sdl.objects.get(sdl=sdl_etap_data["sdl"])
#         else:
#             sdl_etap = Spr_sdl.objects.create(**sdl_etap_data)

#         sdl_set_data = naryad.pop("sdl_set")
#         sdl_set = Sdl_set.objects.create(**sdl_set_data)

#         uslugi = naryad.pop("uslugi")
#         for usl in uslugi:
#             if Pl_uslp.objects.filter(idkv=naryad["idkv"], usl=usl["usl"]).exists():
#                 pass
#             else:
#                 usl = Pl_uslp.objects.create(idkv=naryad["idkv"], **usl)

#         # id_last = Id_last.objects.create(number=naryad["idkv"])
#         # naryad["id_last"] = id_last
#         try:
#             user_etap_link = MyUser.objects.get(mpp=naryad["mpp_etap"])
#             naryad_doc = User_sdl.objects.get(user=user_etap_link)
#             container = Container.objects.get(id=0)
#             new_naryad = It_lab.objects.create(
#                 lpu=lpu,
#                 patient=patient,
#                 opl=opl,
#                 sdl_etap=sdl_etap,
#                 sdl_set=sdl_set,
#                 naryad_doc=naryad_doc,
#                 user_etap_link=user_etap_link,
#                 container=container,
#                 **naryad,
#             )
#             s = Id_last.objects.create(number=new_naryad.id)
#             new_naryad.id_last = s
#             new_naryad.save()
#             # naryad.save()
#             return JsonResponse(
#                 {"status": "ok", "message": "Наряд успешно загружен", "idkv": naryad["idkv"]}, status=200
#             )
#         except Exception:
#             return JsonResponse(
#                 {"status": "error", "message": "Не удалось загрузить наряд", "idkv": naryad["idkv"]}, status=501
#             )

#     # except:
#     #     try:
#     #         json_data = request.body
#     #         naryad = json.loads(json_data)
#     #         return JsonResponse(
#     #             {"status": "error", "message": "Не удалось загрузить наряд", "idkv": naryad["idkv"]}, status=501
#     #         )
#     #     except:
#     #         return JsonResponse(
#     #             {"status": "error", "message": "Не удалось загрузить наряд", "idkv": "неизвестно"}, status=501
#     #         )

#     # except:

#     #     return HttpResponse({"status": "fail", "idkv": request.data["idkv"]}, status=501)
#     # return HttpResponse("")


def signup(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            # load the profile instance created by the signal
            user.save()
            # raw_password = form.cleaned_data.get("password1")

            # login user after signing up
            # user = authenticate(username=user.username, password=raw_password)
            # login(request, user)

            # redirect user to home page
            return redirect("home")
    else:
        form = SignUpForm()
    return render(request, "registration/signup.html", {"form": form})


# def stat_count(request, wait, mpp):
#     if wait == "wait":
#         if mpp == 1:
#             naryad_wait_count = It_lab.objects.filter(dz_etap__isnull=True).filter().count()
#             return HttpResponse(
#                 f"""<b id="wait_count"
#                         hx-get="/naryad/stat_wait/wait/{mpp}"
#                         hx-trigger="load delay:10s"
#                         hx-swap="outerHTML"
#                         hx-target="#wait_count"
#                     >({naryad_wait_count})
#             </b>"""
#             )
#         else:
#             naryad_wait_count = It_lab.objects.filter(Q(id_etap=1) | Q(mpp_etap=mpp), dz_etap__isnull=True).count()
#             return HttpResponse(
#                 f"""<b id="wait_count"
#                         hx-get="/naryad/stat_wait/wait/{mpp}"
#                         hx-trigger="load delay:10s"
#                         hx-swap="outerHTML"
#                         hx-target="#wait_count"
#                     >({naryad_wait_count})
#             </b>"""
#             )
#     elif wait == "inwork":
#         if mpp == 1:
#             naryad_in_work_count = It_lab.objects.filter(dz_etap__isnull=True).distinct("idkv").count()
#             return HttpResponse(
#                 f"""<b id="inwork_count"
#                         hx-get="/naryad/stat_wait/inwork/{mpp}"
#                         hx-trigger="load delay:3s"
#                         hx-swap="outerHTML"
#                         hx-target="#inwork_count"
#                     >({naryad_in_work_count})
#             </b>"""
#             )
#         else:
#             naryad_in_work_count = (
#                 It_lab.objects.filter(dz_etap__isnull=False).exclude(mpp_etap=mpp).distinct("idkv").count()
#             )
#             return HttpResponse(
#                 f"""<b id="inwork_count"
#                         hx-get="/naryad/stat_wait/inwork/{mpp}"
#                         hx-trigger="load delay:3s"
#                         hx-swap="outerHTML"
#                         hx-target="#inwork_count"
#                     >({naryad_in_work_count})
#             </b>"""
#             )
#     return render(request, "naryad/stat_count.html")


# @require_http_methods(["POST", "GET"])
# def login_vue(request, username, password):
#     username_post = request.POST["username"]
#     password_post = request.POST["password"]
#     if request.method == "POST":
#         user = authenticate(request, username=username_post, password=password_post)
#         if user is not None:
#             # login(request, user)
#             try:
#                 user_auth = User_sdl.objects.get(user=user)
#                 dolzh = ""
#                 if len(user_auth.dolzh().split(", ")) > 1:
#                     dolzh_all = user_auth.dolzh().split(", ")
#                     if "Старший техник" in dolzh_all:
#                         dolzh = "Старший техник"
#                     elif "Зав. ортопедией" in dolzh_all:
#                         dolzh = "Зав. ортопедией"
#                     # dolzh = user_auth.dolzh().split(", ")[-1]
#                 else:
#                     dolzh2 = user_auth.dolzh()
#                     if isinstance(dolzh2, list):
#                         dolzh = dolzh2[0]
#                     else:
#                         dolzh = dolzh2

#                 access = ""
#                 if len(user_auth.access_list()) > 1:
#                     access_all = user_auth.access_list()
#                     if "tech_st" in access_all:
#                         access = "tech_st"
#                     elif "zav_ort" in access_all:
#                         access = "zav_ort"
#                     # access = user_auth.access_list()[-1]
#                 else:
#                     access = user_auth.access_list()[0]
#                 # User_sdl.objects.get(user=user).access_list()
#                 # dolzh = user_auth.dolzh()
#                 # access = user_auth.access_list()
#                 # fio_short = user_auth.fio_short()
#                 # data = json.dumps(
#                 #     {
#                 #         "status": "ok",
#                 #         "username": user.login,
#                 #         "mpp": user.mpp,
#                 #         "dolzh": user_auth.dolzh(),
#                 #         "access": user_auth.access_list(),
#                 #         "fio_short": user_auth.fio_short(),
#                 #     }
#                 # )
#                 # access = ",".join(user_auth.access_list())
#                 return JsonResponse(
#                     {
#                         "status": "ok",
#                         "username": user.login,
#                         "mpp": user.mpp,
#                         "dolzh": dolzh,
#                         "access": access,
#                         "fio_short": user_auth.fio_short(),
#                     }
#                 )
#                 # return redirect("naryad_list")
#             except Exception as e:
#                 return JsonResponse({"status": "error", "message": e})
#     else:
#         if username is not None and password is not None:
#             user = authenticate(request, username=username, password=password)
#             if user is not None:
#                 login(request, user)
#                 return redirect("naryad_list")
#     return redirect("login")


# @require_http_methods(["POST", "GET"])
# def update_user_etap_link(request):
#     try:
#         naryads = It_lab.objects.all()
#         count = 0
#         for naryad in naryads:
#             try:
#                 if naryad.mpp_etap > 1:
#                     user = MyUser.objects.get(mpp=naryad.mpp_etap)

#                     naryad.user_etap_link = user
#                     naryad.save()
#                     count += 1
#             except Exception:
#                 pass

#         # It_lab.objects.all().update(user_etap_link=MyUser.objects.get(mpp=F("it_lab.mpp_etap")))
#     except Exception:
#         pass


# @require_http_methods(["POST", "GET"])
# def update_tech_st_sdl_set(request):
#     count = 0
#     try:
#         naryads = It_lab.objects.filter(id_etap=2).all()
#         for naryad in naryads:
#             try:
#                 for_edit_sdl = It_lab.objects.get(idkv=naryad.idkv, id_etap=1)
#                 if for_edit_sdl.mpp_etap != 0:
#                     user = MyUser.objects.get(mpp=for_edit_sdl.mpp_etap)
#                     sdl_set = naryad.sdl_set
#                     sdl_set.tech_st = user.mpp
#                     count += 1
#                     sdl_set.save()
#                 # elif naryad.id_etap > 1:
#                 #     sdl = naryad.sdl_etap.sdl
#                 #     match sdl:
#                 #         case 1:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.doc)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 35:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.tech)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 36:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.pol)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 37:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.lit)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 38:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.cadcam)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp

#             except Exception:
#                 pass
#     except Exception:
#         pass
#     return JsonResponse({"count": count})


# @require_http_methods(["POST", "GET"])
# def update_id_last(request):
#     count = 0
#     try:
#         naryads = It_lab.objects.all()
#         for naryad in naryads:
#             try:
#                 last_naryad = It_lab.objects.filter(idkv=naryad.idkv).order_by("-id_etap").first()
#                 all_naryad = It_lab.objects.filter(idkv=last_naryad.idkv).all()
#                 for one in all_naryad:
#                     if one.id_last is None:
#                         try:
#                             last_etap = Id_last.objects.get(number=last_naryad.id)
#                             one.id_last = last_etap
#                             count += 1
#                             one.save()
#                         except Exception:
#                             last_etap = Id_last.objects.create(number=last_naryad.id)
#                             one.id_last = last_etap
#                             count += 1
#                             one.save()

#                     elif one.id_last.number != last_naryad.id:
#                         try:
#                             last_etap = Id_last.objects.get(number=last_naryad.id)
#                             one.id_last = last_etap
#                             count += 1
#                             one.save()
#                         except Exception:
#                             last_etap = Id_last.objects.create(number=last_naryad.id)
#                             one.id_last = last_etap
#                             count += 1
#                             one.save()
#                 # elif naryad.id_etap > 1:
#                 #     sdl = naryad.sdl_etap.sdl
#                 #     match sdl:
#                 #         case 1:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.doc)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 35:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.tech)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 36:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.pol)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 37:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.lit)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp
#                 #         case 38:
#                 #             user = MyUser.objects.get(mpp=naryad.sdl_set.cadcam)
#                 #             naryad.user_etap = user.login
#                 #             naryad.mpp_etap = user.mpp

#             except Exception:
#                 pass

#     except Exception:
#         pass
#     return JsonResponse({"count": count})


# @require_http_methods(["POST", "GET"])
# def update_doc_nar_link(request):
#     try:
#         naryads = It_lab.objects.all()
#         count = 0
#         for naryad in naryads:
#             try:
#                 user = MyUser.objects.get(mpp=naryad.sdl_set.doc)
#                 # user = User_sdl.objects.get(user=naryad.sdl_set.doc)
#                 user_sdl = User_sdl.objects.get(user=user)
#                 naryad.naryad_doc = user_sdl
#                 naryad.save()
#                 count += 1
#             except Exception:
#                 pass

#     except Exception:
#         pass


# @require_http_methods(["POST", "GET"])
# def update_images_naryad(request):
#     try:
#         naryads = It_lab.objects.all().distinct("nkv")
#         count = 0
#         for naryad in naryads:
#             try:
#                 # user = MyUser.objects.get(mpp=naryad.sdl_set.doc)
#                 # user = User_sdl.objects.get(user=naryad.sdl_set.doc)
#                 images = Images.objects.filter(etap=naryad.id)
#                 for image in images:
#                     image.naryad = naryad.nkv
#                     image.save()
#                     # user_sdl = User_sdl.objects.get(user=user)
#                     # naryad.naryad_doc = user_sdl
#                     # naryad.save()
#                     count += 1
#             except Exception:
#                 pass

#     except Exception:
#         pass


# @require_http_methods(["POST"])
# def kom_etap(request):
#     id = request.POST["id"]
#     kom = request.POST["kom"]
#     try:
#         etap = It_lab.objects.get(id=id)
#         etap.kom_etap = kom
#         etap.save()
#         return JsonResponse({"status": "ok"})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["GET"])
# def count_for_menu(request, mpp: int) -> JsonResponse:
#     try:
#         count_all = It_lab.objects.exclude(id_etap=1).filter(mpp_etap=mpp, dzr__isnull=True).distinct("idkv").count()
#         count = It_lab.objects.exclude(id_etap=1).filter(mpp_etap=mpp, dz_etap__isnull=True).count()
#         # count_waitings = It_lab.objects.filter
#         count_waitings = count_all - count
#         count_rasp = It_lab.objects.filter(id_etap=1, dz_etap__isnull=True).count()
#         return JsonResponse(
#             {"ststus": "ok", "count": count, "count_waitings": count_waitings, "count_rasp": count_rasp}
#         )
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["GET"])
# def spec_by_prof(request):
#     try:
#         list_tech = User_sdl.objects.filter(access__access="tech")
#         tech_list = []
#         for tech in list_tech:
#             dict = {}
#             dict["id"] = tech.user.id
#             dict["name"] = tech.user.get_full_name()
#             dict["mpp"] = tech.user.mpp
#             tech_list.append(dict)
#             # tech_list.append(tech.user)
#         list_lit = User_sdl.objects.filter(access__access="lit")
#         lit_list = []
#         for lit in list_lit:
#             dict = {}
#             dict["id"] = lit.user.id
#             dict["name"] = lit.user.get_full_name()
#             dict["mpp"] = lit.user.mpp
#             lit_list.append(dict)
#         list_cadcam = User_sdl.objects.filter(access__access="cad")
#         cadcam_list = []
#         for cadcam in list_cadcam:
#             dict = {}
#             dict["id"] = cadcam.user.id
#             dict["name"] = cadcam.user.get_full_name()
#             dict["mpp"] = cadcam.user.mpp
#             cadcam_list.append(dict)
#         list_pol = User_sdl.objects.filter(access__access="pol")
#         pol_list = []
#         for pol in list_pol:
#             dict = {}
#             dict["id"] = pol.user.id
#             dict["name"] = pol.user.get_full_name()
#             dict["mpp"] = pol.user.mpp
#             pol_list.append(dict)
#         return JsonResponse(
#             {
#                 "status": "ok",
#                 "list_tech": tech_list,
#                 "list_lit": lit_list,
#                 "list_cadcam": cadcam_list,
#                 "list_pol": pol_list,
#             }
#         )
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["POST"])
# def sdl_set_update(request):
#     try:
#         id = request.POST["id"]
#         sdl_set = Sdl_set.objects.get(id=id)
#         if request.POST["tech"]:
#             sdl_set.tech = request.POST["tech"]
#         if request.POST["lit"]:
#             sdl_set.lit = request.POST["lit"]
#         if request.POST["pol"]:
#             sdl_set.pol = request.POST["pol"]
#         if request.POST["cadcam"]:
#             sdl_set.cadcam = request.POST["cadcam"]
#         sdl_set.save()
#         all_etaps = It_lab.objects.filter(sdl_set=sdl_set, id_etap__gt=1).only("id")
#         for etap in all_etaps:
#             # if etap.id_etap > 1:
#             match etap.sdl_etap.sdl:
#                 case 35:
#                     # tech = request.POST["tech"]
#                     # etap.mpp_etap = tech
#                     user = MyUser.objects.get(mpp=sdl_set.tech)
#                 case 36:
#                     # pol = request.POST["pol"]
#                     # etap.mpp_etap = pol
#                     user = MyUser.objects.get(mpp=sdl_set.pol)
#                 case 37:
#                     # lit = request.POST["lit"]
#                     # etap.mpp_etap = lit
#                     user = MyUser.objects.get(mpp=sdl_set.lit)
#                 case 38:
#                     # cadcam = request.POST["cadcam"]
#                     # etap.mpp_etap = cadcam
#                     user = MyUser.objects.get(mpp=sdl_set.cadcam)
#                 case _:
#                     continue
#             etap.mpp_etap = user.mpp
#             etap.user_etap_link = user
#             etap.user_etap = user.login
#             etap.save()

#         return JsonResponse({"status": "ok"})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": str(inst)})


# @require_http_methods(["GET"])
# def get_usl_by_idkv(request, idkv: int) -> JsonResponse:
#     try:
#         usls = Pl_uslp.objects.filter(idkv=idkv).all()
#         return JsonResponse({"status": "ok", "usl": usls})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["GET"])
# def fix_prof_in_nar(request) -> JsonResponse:
#     try:
#         how_many = 0
#         naryads = (
#             It_lab.objects.filter(id_etap__gt=1)
#             .select_related("lpu", "patient", "opl", "sdl_etap", "sdl_set", "naryad_doc", "user_etap_link")
#             .all()
#         )
#         for item in naryads:
#             if item.sdl_etap.sdl == 1:
#                 item.mpp_etap = item.sdl_set.doc
#             elif item.sdl_etap.sdl == 35:
#                 item.mpp_etap = item.sdl_set.tech
#             elif item.sdl_etap.sdl == 3500:
#                 item.mpp_etap = item.sdl_set.tech
#             elif item.sdl_etap.sdl == 36:
#                 item.mpp_etap = item.sdl_set.pol
#             elif item.sdl_etap.sdl == 37:
#                 item.mpp_etap = item.sdl_set.lit
#             elif item.sdl_etap.sdl == 38:
#                 item.mpp_etap = item.sdl_set.lit
#             how_many += 1
#         return JsonResponse({"how_many": how_many})
#     except Exception as exc:
#         return JsonResponse({"error": exc, "how_many": how_many})


@require_http_methods(["GET"])
def get_lpu_list(request) -> JsonResponse:
    try:
        lpus = Spr_lpu.objects.all()
        how_many = lpus.count()
        # qs_json = serializers.serialize("json", lpus)
        list_lpu = []
        for lpu in lpus:
            dict_lpu = {}
            dict_lpu["lpu"] = lpu.lpu
            dict_lpu["name_lpu"] = lpu.name_lpu
            list_lpu.append(dict_lpu)
        # return HttpResponse(qs_json, content_type="application/json")
        return JsonResponse({"data": list_lpu})
    except Exception as exc:
        return JsonResponse({"error": exc, "how_many": how_many})


# @require_http_methods(["GET"])
# def get_stat_for_zav(request) -> JsonResponse:
#     try:
#         count_nar_income = It_lab.objects.filter(id_etap=0).count()
#         count_nar_rasp = It_lab.objects.filter(id_etap=1).count()
#         count_nar_lab = It_lab.objects.filter(id_etap=2).count()
#         # doc_with_sended_nar = It_lab.objects.exclude(id=F("id_last__number")).filter(id_etap=0).values_list("id")
#         tech_inwork_nar_id = It_lab.objects.exclude(dz_etap__isnull=False).filter(sdl_etap__sdl=35).values_list("id")
#         doc_inwork_nar_id = It_lab.objects.exclude(dz_etap__isnull=False).filter(sdl_etap__sdl=1).values_list("id")
#         # docs_send_nar = {}
#         # for nar in doc_with_sended_nar:
#         #     doc = It_lab.objects.get(id=nar[0]).user_etap_link.get_short_name()
#         #     if doc in docs_send_nar.keys():
#         #         # docs_send_nar[doc] += 1
#         #         docs_send_nar[doc][1] += 1
#         #     else:
#         #         doc_info_list = []
#         #         doc_info_list.append(doc)
#         #         doc_info_list.append(1)
#         #         docs_send_nar[doc] = doc_info_list
#         techs_inwork_nar = {}
#         for nar in tech_inwork_nar_id:
#             tech = It_lab.objects.get(id=nar[0]).user_etap_link
#             tech_short_name = tech.get_short_name()
#             # tech = It_lab.objects.get(id=nar[0]).user_etap_link.get_short_name()
#             tech_mpp = tech.mpp
#             if tech in techs_inwork_nar.keys():
#                 techs_inwork_nar[tech][1] += 1
#             else:
#                 tech_info_list = []
#                 tech_info_list.append(tech_short_name)
#                 tech_info_list.append(1)
#                 tech_info_list.append(tech_mpp)
#                 tech
#                 techs_inwork_nar[tech_short_name] = tech_info_list
#         doc_inwork_nar = {}
#         for nar in doc_inwork_nar_id:
#             # doc = It_lab.objects.get(id=nar[0]).user_etap_link.get_short_name()
#             doc = It_lab.objects.get(id=nar[0]).user_etap_link
#             doc_short_name = doc.get_short_name()
#             doc_mpp = doc.mpp
#             if doc in doc_inwork_nar.keys():
#                 doc_inwork_nar[doc][1] += 1
#             else:
#                 doc_info_list = []
#                 doc_info_list.append(doc_short_name)
#                 doc_info_list.append(1)
#                 doc_info_list.append(doc_mpp)
#                 doc_inwork_nar[doc_short_name] = doc_info_list
#         return JsonResponse(
#             {
#                 "count_nar_income": count_nar_income,
#                 "count_nar_rasp": count_nar_rasp,
#                 "count_nar_lab": count_nar_lab,
#                 "techs_inwork_nar": techs_inwork_nar,
#                 "doc_inwork_nar": doc_inwork_nar,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["POST"])
# def get_stat_for_doc(request, mpp) -> JsonResponse:
#     dn_lg = request.POST.get("dn_lg")
#     dn_lg = datetime.datetime.strptime(dn_lg, "%d.%m.%Y")
#     dk_lg = request.POST.get("dk_lg")
#     dk_lg = datetime.datetime.strptime(dk_lg, "%d.%m.%Y")
#     dn_pl = request.POST.get("dn_pl")
#     dn_pl = datetime.datetime.strptime(dn_pl, "%d.%m.%Y")
#     dk_pl = request.POST.get("dk_pl")
#     dk_pl = datetime.datetime.strptime(dk_pl, "%d.%m.%Y")
#     year = request.POST.get("year")
#     month = request.POST.get("month")
#     try:
#         # date_start_lgot = datetime.datetime(2023, 3, 21)
#         # date_end_lgot = datetime.datetime(2023, 4, 20)
#         # date_start_pd = datetime.datetime(2023, 3, 26)
#         # date_end_pd = datetime.datetime(2023, 4, 25)
#         date_start_lgot = dn_lg
#         date_end_lgot = dk_lg
#         date_start_pd = dn_pl
#         date_end_pd = dk_pl
#         count_nar_done_lgot = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, dzr__range=(date_start_lgot, date_end_lgot), opl__opl=1
#         ).count()
#         count_nar_done_pd = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, dzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3]
#         ).count()
#         count_nar_open_lgot = It_lab.objects.filter(id_etap=0, dzr__isnull=True, mpp_etap=mpp, opl__opl=1).count()
#         count_nar_open_pd = It_lab.objects.filter(
#             id_etap=0, dzr__isnull=True, mpp_etap=mpp, opl__opl__in=[10, 5, 3]
#         ).count()
#         # doc_with_sended_nar = It_lab.objects.exclude(id=F("id_last__number")).filter(id_etap=0).values_list("id")
#         doc_finish_nar_lgot_sum = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, dzr__range=(date_start_lgot, date_end_lgot), opl__opl=1
#         ).aggregate(sum=Sum("stu"))["sum"]
#         doc_pdr_nar_lgot_sum = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, pdzr__range=(date_start_lgot, date_end_lgot), dzr__isnull=True, opl__opl=1
#         ).aggregate(sum=Sum("stu"))["sum"]
#         doc_finish_nar_pd_sum = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, dzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3]
#         ).aggregate(sum=Sum("stu"))["sum"]
#         doc_pdr_nar_pd_sum = It_lab.objects.filter(
#             id_etap=0, mpp_etap=mpp, pdzr__range=[date_start_pd, date_end_pd], dzr__isnull=True, opl__opl__in=[10, 5, 3]
#         ).aggregate(sum=Sum("stu"))["sum"]
#         doc_finish_nar_lgot = list(
#             It_lab.objects.filter(id_etap=0, mpp_etap=mpp, dzr__range=(date_start_lgot, date_end_lgot), opl__opl=1)
#             .select_related("patient")
#             .values("idkv", "nkv", "patient__fam", "patient__im", "patient__ot", "stu", "dou", "dzr")
#         )
#         doc_pdr_nar_lgot = list(
#             It_lab.objects.filter(
#                 id_etap=0, mpp_etap=mpp, pdzr__range=(date_start_lgot, date_end_lgot), dzr__isnull=True, opl__opl=1
#             )
#             .select_related("patient")
#             .values("idkv", "nkv", "patient__fam", "patient__im", "patient__ot", "stu", "dou", "dzr")
#         )
#         doc_finish_nar_pd = list(
#             It_lab.objects.filter(
#                 id_etap=0, mpp_etap=mpp, dzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3]
#             )
#             .select_related("patient")
#             .values("idkv", "nkv", "patient__fam", "patient__im", "patient__ot", "stu", "dou", "dzr")
#         )
#         doc_pdr_nar_pd = list(
#             It_lab.objects.filter(
#                 id_etap=0,
#                 mpp_etap=mpp,
#                 pdzr__range=[date_start_pd, date_end_pd],
#                 dzr__isnull=True,
#                 opl__opl__in=[10, 5, 3],
#             )
#             .select_related("patient")
#             .values("idkv", "nkv", "patient__fam", "patient__im", "patient__ot", "stu", "dou", "dzr")
#         )
#         return JsonResponse(
#             {
#                 "count_nar_done_lgot": count_nar_done_lgot,
#                 "count_nar_done_pd": count_nar_done_pd,
#                 "count_nar_open_lgot": count_nar_open_lgot,
#                 "count_nar_open_pd": count_nar_open_pd,
#                 "doc_finish_nar_lgot_sum": doc_finish_nar_lgot_sum,
#                 "doc_finish_nar_pd_sum": doc_finish_nar_pd_sum,
#                 "doc_finish_nar_lgot": doc_finish_nar_lgot,
#                 "doc_finish_nar_pd": doc_finish_nar_pd,
#                 "doc_pdr_nar_lgot_sum": doc_pdr_nar_lgot_sum,
#                 "doc_pdr_nar_pd_sum": doc_pdr_nar_pd_sum,
#                 "doc_pdr_nar_lgot": doc_pdr_nar_lgot,
#                 "doc_pdr_nar_pd": doc_pdr_nar_pd,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["POST"])
# def get_stat_for_zav2(request, status: int = 0, mpp: int = 0, podr: int = 0, mpp_zav: int = 0) -> JsonResponse:
#     year = int(request.POST.get("year"))
#     month = int(request.POST.get("month"))

#     lgot = request.POST.get("lgot")

#     dn = request.POST.get("dn")
#     dk = request.POST.get("dk")

#     def get_all_nar_by_mpp(
#         mpp: int,
#         fam: str,
#         dn: str,
#         dk: str,
#         opl: str,
#         date_start: datetime,
#         date_end: datetime,
#         year: int,
#         month: int,
#         status_in: int,
#         podr_in: int,
#     ) -> list:
#         podr_list_all: list = []
#         podr_str: str = ""
#         if mpp_zav > 0:
#             user = MyUser.objects.filter(mpp=mpp_zav).first()
#             podrList = (Mpp_podr.objects.filter(mpp=user).first()).podr
#             podr_list_all = [x["lpu_number"] for x in podrList]
#         if podr_in > 0:
#             podr_str = f" and lpu={podr_in}"
#         elif len(podr_list_all) == 1:
#             podr_str = f" and lpu={podr_list_all[0]}"
#         else:
#             podr_tuple_all = tuple(podr_list_all)
#             podr_str = f" and lpu in {podr_tuple_all}"
#         opl_str: str = ""
#         opl_list: list = []
#         if opl == "lgot":
#             opl_str = "opl=1"
#             opl_list = [
#                 1,
#             ]
#         elif opl == "pd":
#             opl_str = "opl in (3, 5, 10)"
#             opl_list = [10, 5, 3]
#         # if status_in == 0:
#         #     status_in = 5

#         select_usl: str = f"""
#             select n_mpp.fam as doctorname, patient.fam, patient.im, patient.ot, pl_uslk.idkv, pl_uslk.nkv,
#             pl_uslk.dou, pl_uslk.dzr as pdzr, pl_uslk.stu from pl_uslk, n_mpp, patient
#             where pl_uslk.vr=n_mpp.mpp
#             and pl_uslk.uid=patient.uid
#             and vr={mpp}
#             and pdog=0
#             and {opl_str}
#             and dzr>='{dn}'
#             and dzr<='{dk}'
#             and status={status_in}
#             {podr_str}"""
#         usl: list = []
#         usl_sum: int = 0
#         lab: list = []
#         lab_sum: int = 0
#         lab_queryset = It_lab.objects.filter(
#             id_etap=0,
#             opl__opl__in=opl_list,
#             sdl_set__doc=mpp,
#         ).select_related("patient")
#         if podr_in > 0:
#             lab_queryset = lab_queryset.filter(lpu__lpu=podr_in)
#         else:
#             lab_queryset = lab_queryset.filter(lpu__lpu__in=podr_list_all)
#         if status_in == 5:
#             lab_queryset = lab_queryset.filter(pdzr__range=[date_start, date_end], dzr__isnull=True, check_zav=False)
#         elif status_in == 6:
#             lab_queryset = lab_queryset.filter(
#                 pdzr__range=[date_start, date_end],
#                 dzr__isnull=True,
#                 check_zav=True,
#                 check_tech=False,
#             )
#         elif status_in == 2:
#             lab_queryset = lab_queryset.filter(
#                 dzr__range=[date_start, date_end],
#                 check_zav=True,
#                 check_tech=True,
#             )
#         lab = list(
#             lab_queryset.values(
#                 "idkv",
#                 "nkv",
#                 "stu",
#                 "dou",
#                 "pdzr",
#                 doctorname=F("naryad_doc__user__fam"),
#                 ot=F("patient__ot"),
#                 im=F("patient__im"),
#                 fam=F("patient__fam"),
#             )
#         )
#         if status_in in (2, 5, 6):
#             usl = db.sel_dict_in_list_lowerkeys(select_usl)
#             for usluga in usl:
#                 usl_sum += usluga["stu"]
#             for nar in lab:
#                 lab_sum += nar["stu"]
#         return [fam, mpp, lab, lab_sum, usl, usl_sum, dn, dk, opl_list, year, month]

#     if status in (2, 5, 6):
#         date_start: datetime = datetime.datetime.strptime(dn, "%d.%m.%Y")
#         dn_str: str = date_start.strftime("%d.%m.%Y")
#         date_end: datetime = datetime.datetime.strptime(dk, "%d.%m.%Y")
#         dk_str: str = date_end.strftime("%d.%m.%Y")
#         # opl: str = "lgot"
#         fam: int = MyUser.objects.filter(mpp=mpp).values_list("fam", flat=True)[0]
#         result: list = get_all_nar_by_mpp(
#             mpp, fam, dn_str, dk_str, lgot, date_start, date_end, year, month, status, podr
#         )
#         return JsonResponse({"doc_finish_2_6": result})

#     def get_stat(dn: str, dk: str, year: int, month: int, opl: str, status_stat: int) -> dict[int, list]:
#         date_start: datetime = datetime.datetime.strptime(dn, "%d.%m.%Y")
#         dn_str: str = date_start.strftime("%d.%m.%Y")
#         date_end: datetime = datetime.datetime.strptime(dk, "%d.%m.%Y")
#         dk_str: str = date_end.strftime("%d.%m.%Y")
#         dict_result: dict[int, dict] = {}
#         # mpp_list: list[dict[str, int | str, str]] = list(MyUser.objects.all().values("mpp", "fam", "im"))
#         mpp_list: list[dict[str, int | str, str]] = list(
#             User_sdl.objects.filter(sdls__sdl=1).values(mpp=F("user__mpp"), fam=F("user__fam"), im=F("user__im"))
#         )
#         mpp_dict = {}
#         for dict_doc in mpp_list:
#             mpp_dict[dict_doc["mpp"]] = {
#                 "mpp": dict_doc["mpp"],
#                 "fam": dict_doc["fam"],
#                 "im": dict_doc["im"],
#                 "count": 0,
#             }
#         if status_stat == 0:
#             status_stat = 5

#         bar = Bar(opl, max=len(mpp_list))
#         for mpp in mpp_list:
#             result: list = get_all_nar_by_mpp(
#                 mpp["mpp"], mpp["fam"], dn_str, dk_str, opl, date_start, date_end, year, month, status_stat, podr
#             )
#             dict_result[mpp["mpp"]] = result
#             bar.next()
#         bar.finish()
#         return dict_result

#     doc_finish_nar = get_stat(dn, dk, year, month, lgot, status)
#     return JsonResponse(
#         {
#             # "doc_finish_nar_pd": doc_finish_nar_pd,
#             "doc_finish_nar": doc_finish_nar,
#         }
#     )


# @require_http_methods(["GET"])
# def return_to_etap_zero(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=0, dz_etap__isnull=False)
#         # for naryad in naryads:
#         #     if naryad.id_last.number == naryad.id:
#         #         naryad.dz_etap = None
#         #         naryad.save()
#         #         count += 1
#         naryads = It_lab.objects.filter(id_etap=1, dz_etap__isnull=True)
#         for naryad in naryads:
#             etap_zero = It_lab.objects.get(idkv=naryad.idkv, id_etap=0)
#             last_number = etap_zero.id_last
#             if etap_zero.kom_etap in (None, ""):
#                 try:
#                     count += 1
#                     last_number.number = etap_zero.id
#                     last_number.save()
#                     etap_zero.dz_etap = None
#                     etap_zero.save()
#                     naryad.delete()
#                 except Exception:
#                     pass
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_dzr_from_arena(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True).distinct("idkv")
#         naryads = It_lab.objects.filter(dzr__isnull=False).distinct("idkv")
#         for naryad in naryads:
#             try:
#                 dzr = db.select(sql.sql_zn_naryad_dzr_uslk.format(idkv=naryad.idkv))[0][0]
#                 if isinstance(dzr, datetime.datetime):
#                     try:
#                         It_lab.objects.filter(idkv=naryad.idkv).update(dzr=dzr)
#                     except Exception:
#                         pass
#                     count += 1
#             except Exception:
#                 pass
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_dzr_from_lab_finish_arena(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         naryads = It_lab.objects.filter(dzr__isnull=False).distinct("idkv")
#         for naryad in naryads:
#             try:
#                 idkv = naryad.idkv
#                 dzr = naryad.dzr
#                 uid = naryad.patient.uid
#                 dou = naryad.dou
#                 nom_teh = naryad.sdl_set.tech
#                 nom_lit = naryad.sdl_set.lit
#                 nom_pol = naryad.sdl_set.pol
#                 nom_cadcam = naryad.sdl_set.cadcam
#                 dou = naryad.dou
#                 dou = f"'{dou}'"
#                 # check_dzr = 0
#                 dzr = dzr.strftime("%d.%m.%Y")
#                 dzr = f"'{dzr}'"
#                 # check_zn = db.select(sql.SLQ_LAB_SEL_ISP.format(idkv=idkv))
#                 # if check_zn == []:
#                 db.write(
#                     sql.SQL_LAB_INS_ISP.format(
#                         idkv=idkv, nom_teh=nom_teh, nom_lit=nom_lit, nom_pol=nom_pol, nom_var="0", dzr=dzr
#                     )
#                 )

#                 check_teh = db.select(sql.SLQ_LAB_CHK_TEH.format(idkv=idkv))
#                 idus = db.select(sql.SLQ_LAB_IDUS.format(idkv=idkv))[0][0]
#                 # if check_zn == []:
#                 if check_teh == []:
#                     idbr = db.proc("NEW_PL_IDBR")[0]
#                 else:
#                     idbr = check_teh[0][0]
#                 # Если есть техник, создать данные в таблице бригад
#                 if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh)) != []:
#                     doc_teh = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh))[0][0] or 0
#                     db.write(
#                         sql.SLQ_LAB_UPD_TEH.format(
#                             uid=uid, idus=idus, nom_teh=nom_teh, idkv=idkv, dou=dou, idbr=idbr, doc=doc_teh
#                         )
#                     )

#                 check_pol = db.select(sql.SLQ_LAB_CHK_POL.format(idkv=idkv))
#                 # if check_zn == []:
#                 if check_pol == []:
#                     idbr = db.proc("NEW_PL_IDBR")[0]
#                 else:
#                     idbr = check_pol[0][0]
#                 if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol)) != []:
#                     doc_pol = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol))[0][0] or 0
#                     db.write(
#                         sql.SLQ_LAB_UPD_POL.format(
#                             uid=uid, idus=idus, nom_pol=nom_pol, idkv=idkv, dou=dou, idbr=idbr, doc=doc_pol
#                         )
#                     )

#                 check_lit = db.select(sql.SLQ_LAB_CHK_LIT.format(idkv=idkv))
#                 # if check_zn == []:
#                 if check_lit == []:
#                     idbr = db.proc("NEW_PL_IDBR")[0]
#                 else:
#                     idbr = check_lit[0][0]
#                 if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit)) != []:
#                     doc_lit = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit))[0][0] or 0
#                     db.write(
#                         sql.SLQ_LAB_UPD_LIT.format(
#                             uid=uid, idus=idus, nom_lit=nom_lit, idkv=idkv, dou=dou, idbr=idbr, doc=doc_lit
#                         )
#                     )

#                 check_cadcam = db.select(sql.SLQ_LAB_CHK_CADCAM.format(idkv=idkv))
#                 # if check_zn == []:
#                 if check_cadcam == []:
#                     idbr = db.proc("NEW_PL_IDBR")[0]
#                 else:
#                     idbr = check_cadcam[0][0]
#                 if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam)) != []:
#                     doc_cadcam = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam))[0][0] or 0
#                     db.write(
#                         sql.SLQ_LAB_UPD_CADCAM.format(
#                             uid=uid, idus=idus, nom_cadcam=nom_cadcam, idkv=idkv, dou=dou, idbr=idbr, doc=doc_cadcam
#                         )
#                     )

#                 # если дата формата дд.мм.гг то запись на отправку---------------------------------
#                 # s = db.select(f"select dzr, status, pdog from pl_uslk where idkv={idkv}")
#                 # if s != []:
#                 # if s[0][0] is None:
#                 db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=5, dzr=dzr))
#                 count += 1
#                 # send_telegram(f"Установлен dzr для наряда: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}")
#                 # else:
#                 #     db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=3, dzr=dzr))
#                 # send_telegram(f"Успешно создано закрытие наряда idkv: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}")
#             except Exception as exerr:
#                 send_telegram(f"Наряд idkv: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}, ошибка{exerr}")
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_dzr_from_lab_finish_arena2(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         sq_select_double = """SELECT idkv,COUNT(*)
#                     FROM pl_uslt
#                     GROUP BY idkv;"""
#         result = db.select(sq_select_double)
#         for one in result:
#             if one[1] > 1:
#                 sql_two_row = """
#                 SELECT *
#                 from pl_uslt
#                 Where (pl_uslt.idkv = {idkv});"""
#                 result2 = db.select(sql_two_row.format(idkv=one[0]))
#                 # delete_sql = """delete from pl_uslt where idkv={idkv}"""
#                 # db.write(delete_sql.format(idkv=one[0]))
#                 result3 = result2[1]

#                 idkv = result3[0]
#                 # nom_teh = result3[1]
#                 # nom_lit = result3[3]
#                 # nom_pol = result3[4]
#                 dzr = result3[7]
#                 dzr = dzr.strftime("%d.%m.%Y")
#                 dzr = f"'{dzr}'"

#         db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=3, dzr=dzr))
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_notequal_dzr(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         # sq_select_double = """SELECT idkv,COUNT(*)
#         #             FROM pl_uslt
#         #             GROUP BY idkv;"""
#         select_dzr = """SELECT idkv, nkv, dzr, stu from pl_uslk where dzr>='01.03.2023' and dzr<='28.08.2023' and vr not in (8, 707, 241, 214)"""
#         # result = db.select(sq_select_double)
#         result = db.sel_dict_in_list_desc(select_dzr)
#         count_all = len(result)
#         # bar = Bar("get_notequal_dzr", max=count_all)

#         for one in result:
#             # from_django = It_lab()
#             count_all -= 1
#             try:
#                 if It_lab.objects.filter(nkv=one["NKV"], id_etap=0).distinct("nkv").exists():
#                     from_django = It_lab.objects.get(nkv=one["NKV"], id_etap=0)
#                     if one["DZR"].date() != from_django.dzr:
#                         # if one["DZR"] == datetime.datetime(2023, 3, 25, 0, 0):
#                         It_lab.objects.filter(nkv=one["NKV"]).update(dzr=one["DZR"].date())
#                         count += 1
#                 # It_lab.objects.filter(idkv=from_django.idkv).update(dzr=one["DZR"])
#                 # pass
#                 # It_lab.objects.filter(idkv=one["IDKV"]).update(dzr=datetime.date(2023, 3, 25))
#                 # if one["STU"] != from_django.stu:
#                 #     pass
#             except Exception as exc:
#                 pass

#         #     bar.next()
#         # bar.finish()
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_notequal_dzr2(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         # sq_select_double = """SELECT idkv,COUNT(*)
#         #             FROM pl_uslt
#         #             GROUP BY idkv;"""
#         naryads = It_lab.objects.filter(
#             opl__opl=1, dzr__isnull=False, pdzr__isnull=False, check_zav=True, check_tech=True, id_etap=0
#         )

#         # naryads = It_lab.objects.filter(dzr__range=["2023-06-20", "2023-07-31"]).distinct("nkv")
#         for nar in naryads:
#             count += 1
#             select_dzr = f"""SELECT idkv, nkv, dzr, stu from pl_uslk where nkv={nar.nkv}"""
#             try:
#                 result = db.sel_dict_in_list_desc(select_dzr)[0]
#                 if result["DZR"] is None:
#                     print(result)
#                 if result["DZR"].date() != nar.dzr:
#                     print("dzr: ", result["NKV"], result["DZR"], "from_django; ", nar.dzr)
#                 else:
#                     print(nar.nkv, nar.dzr, result["DZR"])
#             except Exception as exer:
#                 print(exer)

#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_zero_birg(request) -> JsonResponse:
#     try:
#         count = 0
#         # naryads = It_lab.objects.filter(id_etap=1, dzr__isnull=True)
#         # sq_select_double = """SELECT idkv,COUNT(*)
#         #             FROM pl_uslt
#         #             GROUP BY idkv;"""
#         # select_dzr = """SELECT idkv, nkv, dzr, stu from pl_uslk where dzr>='01.11.2022' and dzr<='25.03.2023'"""
#         # result = db.select(sq_select_double)
#         # result = db.sel_dict_in_list_desc(select_dzr)
#         naryads = It_lab.objects.filter(dzr__isnull=False, id_etap=0).all().only("idkv", "sdl_set")
#         for naryad in naryads:
#             # if naryad.idkv == 1110513:
#             # Техник
#             if naryad.sdl_set.tech != 0:
#                 from_db = db.sel_dict_in_list_desc(f"select * from pl_uslb where idkv={naryad.idkv} and sdl=35")
#                 if from_db[0]["MPP"] != naryad.sdl_set.tech:
#                     get_doc = db.sel_dict_in_list_desc(
#                         f"SELECT doc from n_doc where mpp={naryad.sdl_set.tech} and mol=1;"
#                     )
#                     try:
#                         db.write(
#                             f"""update pl_uslb set mpp='{naryad.sdl_set.tech}',
#                             doc='{get_doc[0]['DOC']}'
#                             where idkv={naryad.idkv}
#                             and sdl=35"""
#                         )
#                     except Exception:
#                         pass
#             # Полировщик
#             if naryad.sdl_set.pol != 0:
#                 from_db = db.sel_dict_in_list_desc(f"select * from pl_uslb where idkv={naryad.idkv} and sdl=36")
#                 if from_db[0]["MPP"] != naryad.sdl_set.pol:
#                     get_doc = db.sel_dict_in_list_desc(
#                         f"SELECT doc from n_doc where mpp={naryad.sdl_set.pol} and mol=1;"
#                     )
#                     if len(get_doc) > 1:
#                         break
#                     try:
#                         db.write(
#                             f"""update pl_uslb set mpp='{naryad.sdl_set.pol}', doc='{get_doc[0]['DOC']}'
#                             where idkv={naryad.idkv}
#                             and sdl=36"""
#                         )
#                     except Exception:
#                         pass
#             # Литейщик
#             if naryad.sdl_set.lit != 0:
#                 from_db = db.sel_dict_in_list_desc(f"select * from pl_uslb where idkv={naryad.idkv} and sdl=37")
#                 if from_db[0]["MPP"] != naryad.sdl_set.lit:
#                     get_doc = db.sel_dict_in_list_desc(
#                         f"SELECT doc from n_doc where mpp={naryad.sdl_set.lit} and mol=1;"
#                     )
#                     if len(get_doc) > 1:
#                         break
#                     try:
#                         db.write(
#                             f"update pl_uslb set mpp='{naryad.sdl_set.lit}', doc='{get_doc[0]['DOC']}' where idkv={naryad.idkv} and sdl=37"
#                         )
#                     except Exception:
#                         pass
#             # Сканирование cadcam
#             if naryad.sdl_set.cadcam != 0:
#                 from_db = db.sel_dict_in_list_desc(f"select * from pl_uslb where idkv={naryad.idkv} and sdl=38")
#                 if from_db[0]["MPP"] != naryad.sdl_set.cadcam:
#                     get_doc = db.sel_dict_in_list_desc(
#                         f"SELECT doc from n_doc where mpp={naryad.sdl_set.cadcam} and mol=1;"
#                     )
#                     if len(get_doc) > 1:
#                         break
#                     try:
#                         db.write(
#                             f"update pl_uslb set mpp='{naryad.sdl_set.cadcam}', doc='{get_doc[0]['DOC']}' where idkv={naryad.idkv} and sdl=38"
#                         )
#                     except Exception:
#                         pass
#             count += 1
#         # for one in result:
#         #     count += 1
#         #     from_django = It_lab()
#         #     try:
#         #         from_django = It_lab.objects.get(id_etap=0, idkv=one["IDKV"])
#         #         if one["DZR"].date() != from_django.dzr:
#         #             if one["DZR"] == datetime.datetime(2023, 3, 25, 0, 0):
#         #                 # It_lab.objects.filter(idkv=one["IDKV"]).update(dzr=datetime.date(2023, 3, 25))
#         #         if one["STU"] != from_django.stu:
#         #     except Exception as textexc:
#         #         pass

#         # check_teh = db.select(sql.SLQ_LAB_CHK_TEH.format(idkv=idkv))
#         # idus = db.select(sql.SLQ_LAB_IDUS.format(idkv=idkv))[0][0]

#         # if check_teh == []:
#         #     idbr = db.proc("NEW_PL_IDBR")[0]
#         # else:
#         #     idbr = check_teh[0][0]

#         # if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh)) != []:
#         #     doc_teh = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_teh))[0][0] or 0
#         #     db.write(
#         #         sql.SLQ_LAB_UPD_TEH.format(
#         #             uid=uid, idus=idus, nom_teh=nom_teh, idkv=idkv, dou=dou, idbr=idbr, doc=doc_teh
#         #         )
#         #     )

#         # check_pol = db.select(sql.SLQ_LAB_CHK_POL.format(idkv=idkv))
#         # # if check_zn == []:
#         # if check_pol == []:
#         #     idbr = db.proc("NEW_PL_IDBR")[0]
#         # else:
#         #     idbr = check_pol[0][0]
#         # if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol)) != []:
#         #     doc_pol = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_pol))[0][0] or 0
#         #     db.write(
#         #         sql.SLQ_LAB_UPD_POL.format(
#         #             uid=uid, idus=idus, nom_pol=nom_pol, idkv=idkv, dou=dou, idbr=idbr, doc=doc_pol
#         #         )
#         #     )

#         # check_lit = db.select(sql.SLQ_LAB_CHK_LIT.format(idkv=idkv))

#         # if check_lit == []:
#         #     idbr = db.proc("NEW_PL_IDBR")[0]
#         # else:
#         #     idbr = check_lit[0][0]
#         # if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit)) != []:
#         #     doc_lit = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_lit))[0][0] or 0
#         #     db.write(
#         #         sql.SLQ_LAB_UPD_LIT.format(
#         #             uid=uid, idus=idus, nom_lit=nom_lit, idkv=idkv, dou=dou, idbr=idbr, doc=doc_lit
#         #         )
#         #     )

#         # check_cadcam = db.select(sql.SLQ_LAB_CHK_CADCAM.format(idkv=idkv))

#         # if check_cadcam == []:
#         #     idbr = db.proc("NEW_PL_IDBR")[0]
#         # else:
#         #     idbr = check_cadcam[0][0]
#         # if db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam)) != []:
#         #     doc_cadcam = db.select(sql.SQL_LAB_SEL_DOC.format(mpp=nom_cadcam))[0][0] or 0
#         #     db.write(
#         #         sql.SLQ_LAB_UPD_CADCAM.format(
#         #             uid=uid, idus=idus, nom_cadcam=nom_cadcam, idkv=idkv, dou=dou, idbr=idbr, doc=doc_cadcam
#         #         )
#         #     )

#         # db.write(sql.sql_zn_naryad_update_uslk.format(idkv=idkv, status=3, dzr=dzr))
#         # count += 1

#         #     except Exception as exerr:
#         #         send_telegram(f"Наряд idkv: {naryad.idkv}, nkv: {naryad.nkv}, dzr: {dzr}, ошибка{exerr}")
#         return JsonResponse(
#             {
#                 "count_update": count,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def period_date(request) -> JsonResponse:
#     select_dates = "select id, nmonth, dn_pl, dk_pl, dn_lg, dk_lg, years, months from it_period_rep where razdel=1"
#     try:
#         dates = db.sel_dict_in_list_desc(select_dates)
#         return JsonResponse(
#             {
#                 "dates": dates,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def get_naryad_usl(request, naryad) -> JsonResponse:
#     select_naryad = f"select n_mpp.nmpp, pl_uslk.idkv, pl_uslk.uid, pl_uslk.opl, pl_uslk.pdog, pl_uslk.dou, pl_uslk.dzr, pl_uslk.stu, pl_uslk.nkv, pl_uslk.vr, pl_uslk.lpu, pl_uslk.status from pl_uslk, n_mpp where n_mpp.mpp=pl_uslk.vr and nkv={naryad} and pdog=0 and gr_otd=2"
#     try:
#         request_result = db.sel_dict_in_list_desc(select_naryad)
#         if request_result == []:
#             request_result = [
#                 {
#                     "NMPP": "пусто",
#                     "IDKV": 0,
#                     "UID": 0,
#                     "OPL": 0,
#                     "PDOG": 0,
#                     "DOU": datetime.datetime(2023, 4, 19, 0, 0),
#                     "DZR": 0,
#                     "STU": 0.0,
#                     "NKV": 0,
#                     "VR": 0,
#                     "LPU": 0,
#                     "STATUS": 0,
#                 }
#             ]
#         else:
#             match request_result[0]["OPL"]:
#                 case 1:
#                     request_result[0]["OPL"] = "Бюджет"
#                 case 3:
#                     request_result[0]["OPL"] = "ДМС"
#                 case 5:
#                     request_result[0]["OPL"] = "Договорные услуги"
#                 case 10:
#                     request_result[0]["OPL"] = "Платные услуги"

#         return JsonResponse(
#             {
#                 "naryad": request_result,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["POST"])
# def get_nar_usl_doc(request, mpp) -> JsonResponse:
#     dn_lg = request.POST.get("dn_lg")
#     dn_lg = datetime.datetime.strptime(dn_lg, "%d.%m.%Y")
#     dk_lg = request.POST.get("dk_lg")
#     dk_lg = datetime.datetime.strptime(dk_lg, "%d.%m.%Y")
#     dn_pl = request.POST.get("dn_pl")
#     dn_pl = datetime.datetime.strptime(dn_pl, "%d.%m.%Y")
#     dk_pl = request.POST.get("dk_pl")
#     dk_pl = datetime.datetime.strptime(dk_pl, "%d.%m.%Y")
#     try:
#         # date_start_lgot = datetime.datetime(2023, 3, 21)
#         # date_end_lgot = datetime.datetime(2023, 4, 20)
#         # date_start_pd = datetime.datetime(2023, 3, 26)
#         # date_end_pd = datetime.datetime(2023, 4, 25)
#         date_start_lgot = dn_lg
#         date_end_lgot = dk_lg
#         date_start_pd = dn_pl
#         date_end_pd = dk_pl

#         request_lgot = f"select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr from patient, pl_uslk where patient.uid=pl_uslk.uid and pdog=0 and gr_otd=2 and vr={mpp} and opl=1 and dzr>='{date_start_lgot}' and dzr<='{date_end_lgot}' and status in (2, 3)"
#         doc_finish_nar_usl_lgot = db.sel_dict_in_list_desc(request_lgot)
#         count_finish_nar_usl_lgot = len(doc_finish_nar_usl_lgot)
#         sum_lgot = sum([x["STU"] for x in doc_finish_nar_usl_lgot])
#         request_pdr_lgot = f"""
#             select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr
#             from patient, pl_uslk
#             where patient.uid=pl_uslk.uid
#             and pdog=0
#             and gr_otd=2
#             and vr={mpp}
#             and opl=1
#             and dzr>='{date_start_lgot}'
#             and dzr<='{date_end_lgot}'
#             and status=5"""
#         doc_pdr_nar_usl_lgot = db.sel_dict_in_list_desc(request_pdr_lgot)
#         # count_finish_nar_usl_lgot = len(doc_finish_nar_usl_lgot)
#         pdr_sum_lgot = sum([x["STU"] for x in doc_pdr_nar_usl_lgot])
#         request_pd = f"select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr from patient, pl_uslk where patient.uid=pl_uslk.uid and pdog=0 and gr_otd=2 and vr={mpp} and opl in (3, 5, 10) and dzr>='{date_start_pd}' and dzr<='{date_end_pd}' and status in (2, 3)"
#         doc_finish_nar_usl_pd = db.sel_dict_in_list_desc(request_pd)
#         count_finish_nar_usl_pd = len(doc_finish_nar_usl_pd)
#         sum_pd = sum([x["STU"] for x in doc_finish_nar_usl_pd])
#         request_pdr_pd = f"select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr from patient, pl_uslk where patient.uid=pl_uslk.uid and pdog=0 and gr_otd=2 and vr={mpp} and opl in (3, 5, 10) and dzr>='{date_start_pd}' and dzr<='{date_end_pd}' and status=5"
#         doc_pdr_nar_usl_pd = db.sel_dict_in_list_desc(request_pdr_pd)
#         # count_finish_nar_usl_pd = len(doc_finish_nar_usl_pd)
#         pdr_sum_pd = sum([x["STU"] for x in doc_pdr_nar_usl_pd])
#         return JsonResponse(
#             {
#                 "doc_finish_nar_usl_lgot": doc_finish_nar_usl_lgot,
#                 "doc_finish_nar_usl_pd": doc_finish_nar_usl_pd,
#                 "count_finish_nar_usl_lgot": count_finish_nar_usl_lgot,
#                 "count_finish_nar_usl_pd": count_finish_nar_usl_pd,
#                 "sum_lgot": sum_lgot,
#                 "sum_pd": sum_pd,
#                 "doc_pdr_nar_usl_lgot": doc_pdr_nar_usl_lgot,
#                 "doc_pdr_nar_usl_pd": doc_pdr_nar_usl_pd,
#                 "pdr_sum_lgot": pdr_sum_lgot,
#                 "pdr_sum_pd": pdr_sum_pd,
#             }
#         )
#     except Exception as exc:
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def close_usl_nar(request, naryad) -> JsonResponse:
#     today = datetime.date.today().strftime("%d.%m.%Y")
#     # today = datetime.date.today()
#     request = f"update pl_uslk set dzr='{today}', status=5 where nkv={naryad}"
#     try:
#         db.write(request)
#         request_result = db.sel_dict_in_list_desc(request)
#         return JsonResponse(
#             {
#                 "naryad": request_result,
#             }
#         )
#     except Exception as exc:
#         print(exc)
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def resend_nar_lab(request) -> JsonResponse:
#     # today = datetime.date.today().strftime("%d.%m.%Y")
#     # today = datetime.date.today()
#     request = "update pl_uslk set status_exp=0 where dzr is null and dou>='08.06.2023' and status_exp=201"
#     try:
#         db.write(request)
#     except Exception as error_mes:
#         print(error_mes)
#     # try:
#     #     naryads = db.sel_dict_in_list_desc(request)
#     #     for naryad in naryads:
#     #         request_w = f"update pl_uslk set status_exp='0' where nkv={naryad['NKV']}"
#     #         try:
#     #             db.write(request_w)
#     #         except Exception as error_mes:
#     #             print(error_mes)
#     # request_result = db.sel_dict_in_list_desc(request)
#     return JsonResponse(
#         {
#             "naryad": "done",
#         }
#     )


# @require_http_methods(["GET"])
# def del_nar(request, naryad) -> JsonResponse:
#     try:
#         It_lab.objects.filter(idkv=naryad).delete()
#         return JsonResponse(
#             {
#                 "ok": "deleted",
#             }
#         )
#     except Exception as exc:
#         print(exc)
#         return JsonResponse({"error": exc})


# @require_http_methods(["GET"])
# def nar_proverka_perioda(request) -> JsonResponse:
#     list_nar = [
#         1061269,
#         1061940,
#     ]
#     for nar in list_nar:
#         try:
#             naryad = It_lab.objects.get(id_etap=0, nkv=nar)
#         except Exception as exc:
#             print(exc)
#             # return JsonResponse({"error": exc})
#     return JsonResponse(
#         {
#             "ok": "selected",
#         }
#     )


# @require_http_methods(["GET"])
# def proverka_brigad(request) -> JsonResponse:
#     # start_date = (datetime.datetime(2023, 4, 21, 0, 0),)
#     naryads = It_lab.objects.filter(dzr__gt="2023-04-20", id_etap=0)
#     for nar in naryads:
#         if nar.mpp_etap not in [8, 707, 214, 241]:
#             select_35 = f"select * from pl_uslb where idkv={nar.idkv} and sdl=35"
#             from_arena = db.sel_dict_in_list_desc(select_35)
#             if from_arena == []:
#                 print("idkv: ", nar.idkv, nar.dzr, "35 отсутствует")
#             else:
#                 if from_arena[0]["MPP"] != nar.sdl_set.tech:
#                     print(
#                         "idkv: ", nar.idkv, nar.dzr, "техник не сходится", from_arena[0]["MPP"], " - ", nar.sdl_set.tech
#                     )
#             select_36 = f"select * from pl_uslb where idkv={nar.idkv} and sdl=36"
#             from_arena = db.sel_dict_in_list_desc(select_36)
#             if from_arena == []:
#                 print("idkv: ", nar.idkv, nar.dzr, "36 отсутствует")
#             else:
#                 if from_arena[0]["MPP"] != nar.sdl_set.pol:
#                     print(
#                         "idkv: ",
#                         nar.idkv,
#                         nar.dzr,
#                         "полировщик не сходится",
#                         from_arena[0]["MPP"],
#                         " - ",
#                         nar.sdl_set.pol,
#                     )
#             select_37 = f"select * from pl_uslb where idkv={nar.idkv} and sdl=37"
#             from_arena = db.sel_dict_in_list_desc(select_37)
#             if from_arena == []:
#                 print("idkv: ", nar.idkv, nar.dzr, "37 отсутствует")
#             else:
#                 if from_arena[0]["MPP"] != nar.sdl_set.lit:
#                     print(
#                         "idkv: ",
#                         nar.idkv,
#                         nar.dzr,
#                         "литейщик не сходится",
#                         from_arena[0]["MPP"],
#                         " - ",
#                         nar.sdl_set.lit,
#                     )
#             select_38 = f"select * from pl_uslb where idkv={nar.idkv} and sdl=38"
#             from_arena = db.sel_dict_in_list_desc(select_38)
#             if from_arena == []:
#                 print("idkv: ", nar.idkv, nar.dzr, "38 отсутствует")
#             else:
#                 if from_arena[0]["MPP"] != nar.sdl_set.cadcam:
#                     print(
#                         "idkv: ",
#                         nar.idkv,
#                         nar.dzr,
#                         "кадкам не сходится",
#                         from_arena[0]["MPP"],
#                         " - ",
#                         nar.sdl_set.cadcam,
#                     )
#             # try:
#             #     naryad = It_lab.objects.get(id_etap=0, nkv=nar)
#             #     print(naryad.dzr)
#             # except Exception as exc:
#             #     print(exc)
#             # return JsonResponse({"error": exc})
#     return JsonResponse(
#         {
#             "ok": "selected",
#         }
#     )


# @require_http_methods(["GET"])
# def open_closed_etaps(request) -> JsonResponse:
#     list_last_nar = It_lab.objects.filter(id_etap=0, dzr__isnull=True).values_list("id_last__number")
#     count = 0
#     for nar in list_last_nar:
#         id = nar[0]
#         naryad = It_lab.objects.get(id=id)
#         if naryad.dz_etap is not None:
#             count += 1
#             naryad.dz_etap = None
#             naryad.save()
#     return JsonResponse(
#         {
#             "ok": "selected",
#         }
#     )


# @require_http_methods(["GET"])
# def generate_containers(request) -> JsonResponse:
#     count = 1
#     for i in range(1, 1000):
#         Container.objects.create(id=i)
#         count += 1
#     return JsonResponse(
#         {
#             "ok": count,
#         }
#     )


# @require_http_methods(["GET"])
# def get_container(request, container, id_naryad) -> JsonResponse:
#     naryad = It_lab.objects.get(id=id_naryad)
#     if container >= 1 and container <= 1000:
#         # if container in range(1,1001):
#         get_container = Container.objects.get(id=container)
#         if get_container.used is True and get_container.nkv > 0:
#             naryads_container = It_lab.objects.filter(nkv=get_container.nkv, id_etap=0, dzr__isnull=True)
#             if len(naryads_container) > 0:
#                 return JsonResponse({"free": True})
#         if get_container.used is False:
#             return JsonResponse(
#                 {
#                     "free": True,
#                 }
#             )
#         else:
#             return JsonResponse(
#                 {
#                     "free": False,
#                 }
#             )
#     else:
#         return JsonResponse(
#             {
#                 "free": False,
#             }
#         )
#         return JsonResponse(
#             {
#                 "free": False,
#             }
#         )


# @require_http_methods(["GET"])
# def check_dzetap(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(dzr__isnull=True)
#     for naryad in naryads:
#         if naryad.dzr is None and naryad.dz_etap is None:
#             if It_lab.objects.filter(nkv=naryad.nkv, id_etap=naryad.id_etap + 1).exists():
#                 print(naryad.nkv)
#     return JsonResponse(
#         {
#             "free": False,
#         }
#     )


# @require_http_methods(["GET"])
# def check_dzetap2(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(dzr__isnull=True, dz_etap__isnull=False).distinct("nkv")
#     for naryad in naryads:
#         new_nar = It_lab.objects.filter(nkv=naryad.nkv, dzr__isnull=True).order_by("-id_etap").distinct("id_etap")
#     return JsonResponse(
#         {
#             "free": False,
#         }
#     )


# @require_http_methods(["GET"])
# def check_container(request) -> JsonResponse:
#     # containers = Container.objects.filter(used=True, nkv__gt=0)
#     containers = Container.objects.filter(used=True)
#     count_edit = 0
#     for cont in containers:
#         # container = Container.objects.get(id=cont.nkv)
#         if It_lab.objects.filter(container=cont, dzr__isnull=True, id_etap=0).exists():
#             pass
#         else:
#             cont.used = False
#             cont.nkv = 0
#             cont.save()
#             count_edit += 1
#     return JsonResponse({"free": False, "edit": count_edit})


# @require_http_methods(["GET"])
# def check_container_multiple(request, id_naryad: int = 0) -> JsonResponse:
#     # containers = Container.objects.filter(used=True, nkv__gt=0)
#     if id_naryad > 0:
#         nar = It_lab.objects.get(id=id_naryad)
#         naryads = (
#             It_lab.objects.exclude(nkv=nar.nkv)
#             .filter(patient=nar.patient, sdl_set__doc=nar.sdl_set.doc, dzr__isnull=True, id_etap=0, container__id__gt=0)
#             .values("container__id", "nkv", "dou", "stu")
#         )
#         # naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=True, container__id__gt=0).values(
#         #     "container__id", "patient__id", "sdl_set__doc", "nkv"
#         # )
#     # count_edit: int = 0
#     # testcontainer_id: int = 888
#     # return JsonResponse({"status": "ok", "container": testcontainer_id})
#     # naryads_test = (
#     #     It_lab.objects.exclude(nkv=nar.nkv)
#     #     .filter(dzr__isnull=True, id_etap=0, container__id__gt=0)
#     #     .values("container__id", "nkv", "dou", "stu")
#     # )[:5]
#     nar_list: list = list(naryads)
#     for naryad in naryads:
#         nar_list.append(naryad)
#     if len(nar_list) > 0:
#         return JsonResponse({"status": "ok", "container": nar_list})
#     else:
#         return JsonResponse({"status": "false"})
#     # containers = Container.objects.filter(used=True)
#     # count_edit = 0
#     # for cont in containers:
#     #     # container = Container.objects.get(id=cont.nkv)
#     #     if It_lab.objects.filter(container=cont, dzr__isnull=True, id_etap=0).exists():
#     #         pass
#     #     else:
#     #         cont.used = False
#     #         cont.nkv = 0
#     #         cont.save()
#     #         count_edit += 1


# @require_http_methods(["GET"])
# def container_info(request, container_id) -> JsonResponse:
#     query_info = Container.objects.filter(id=container_id).first()
#     # print(query_info)
#     info = query_info.get_info()
#     # print(info)
#     if info:
#         return JsonResponse({"used": True, "info": info})
#     else:
#         return JsonResponse({"used": False})


# @require_http_methods(["GET"])
# def bonus_naryad(request, naryad_id) -> JsonResponse:
#     current_naryad = It_lab.objects.get(id=naryad_id)
#     try:
#         other_naryads = (
#             It_lab.objects.exclude(nkv=current_naryad.nkv)
#             .exclude(container=Container.objects.get(id=0))
#             .filter(patient=current_naryad.patient, dzr__isnull=True, sdl_set__doc=current_naryad.sdl_set.doc)
#             .values("id", "nkv", "stu", "container", "container__id", "container__nkv")
#         )
#     except Exception:
#         pass
#     if other_naryads:
#         return JsonResponse({"open_naryads": True, "naryads": list(other_naryads)})
#     else:
#         return JsonResponse({"open_naryads": False})


# @require_http_methods(["GET"])
# def check_all_etap_close(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=False)
#     list_nars = []

#     bar = Bar("check_all_etap_close", max=naryads.count())

#     for nar in naryads:
#         all_etaps = It_lab.objects.filter(nkv=nar.nkv, dzr__isnull=True)
#         if len(all_etaps) > 0:
#             It_lab.objects.filter(nkv=nar.nkv, id_etap__gt=0).update(dzr=nar.dzr, dz_etap=nar.dzr)
#             list_nars.append(nar.nkv)
#         bar.next()
#     bar.finish()
#     return JsonResponse({"nars_count": len(list_nars), "list_naryads": list_nars})


# @require_http_methods(["GET"])
# def check_bonus_naryads(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=True, container__id__gt=0)
#     list_patients = {}
#     list_ids = {}
#     bar = Bar("check_all_etap_close", max=naryads.count())

#     for nar in naryads:
#         if nar.patient.id in list_patients:
#             list_patients[nar.patient.id] += 1
#         else:
#             list_patients[nar.patient.id] = 1
#         bar.next()
#     bar.finish()
#     list_patients_short = []
#     for key, value in list_patients.items():
#         if value > 1:
#             list_patients_short.append(key)
#     naryads_by_patient = It_lab.objects.filter(patient__id=list_patients_short[0]).distinct("nkv")
#     naryad_id_list = []
#     for nar in naryads_by_patient:
#         naryad_id_list.append(nar.id)
#     return JsonResponse({"patient_list": len(list_patients_short), "naryad_id_list": naryad_id_list})


# @require_http_methods(["POST"])
# def not_lab_naryads(request) -> JsonResponse:
#     nars = request.POST["nars"]
#     try:
#         sql = f"select nkv, dou, dzr, stu, vr from pl_uslk where nkv in ({nars})"
#         arena_nars = db.sel_dict_in_list_desc(sql)
#         result_nars = {}
#         for nar in arena_nars:
#             if nar["DZR"] is not None:
#                 nar["DZR"] = nar["DZR"].strftime("%Y-%m-%d")
#             else:
#                 nar["DZR"] = datetime.datetime.today().strftime("%Y-%m-%d")
#                 result_nars[nar["NKV"]] = nar
#         return JsonResponse({"status": "ok", "arena_nars": result_nars})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["POST"])
# def zav_report_finish(request) -> JsonResponse:
#     nars_lab_all = request.POST["nars_lab_all"]
#     nars_lab_ok = request.POST["nars_lab_ok"]
#     usl_numbers = request.POST["usl_numbers_all"]
#     nars_usl_ok = request.POST["nars_usl_ok"]
#     dn = request.POST["dn"]
#     dk = request.POST["dk"]
#     opl = request.POST["opl"]
#     year = request.POST["year"]
#     month = request.POST["month"]
#     mpp = request.POST["mpp"]

#     nars_lab_all = json.loads(nars_lab_all)
#     usl_numbers = json.loads(usl_numbers)
#     nars_lab_ok = json.loads(nars_lab_ok)
#     nars_usl_ok = json.loads(nars_usl_ok)
#     for one_nar in nars_lab_ok:
#         try:
#             It_lab.objects.filter(nkv=one_nar["nkv"]).update(check_zav=True)
#         except Exception as error1:
#             print(error1)
#         try:
#             db.write(f"Update pl_uslk set status=6 where nkv={one_nar['nkv']}")
#         except Exception as error2:
#             print(error2)
#     for one_usl in nars_usl_ok:
#         try:
#             db.write(f"update pl_uslk set status=6 where nkv={one_usl['nkv']}")
#         except Exception as error3:
#             print(error3)
#     stu_lab = 0
#     for nar in nars_lab_ok:
#         stu_lab += nar["stu"]
#     stu_usl = 0
#     for usl in nars_usl_ok:
#         stu_usl += usl["stu"]
#     stu_all = stu_lab + stu_usl
#     nars_lab_cancel = []
#     nars_lab_cancel = nars_lab_all.copy()
#     for one in nars_lab_ok:
#         if one["nkv"] in nars_lab_cancel:
#             nars_lab_cancel.remove(one["nkv"])
#     nars_usl_cancel = []
#     nars_usl_cancel = usl_numbers.copy()
#     for two in nars_usl_ok:
#         if two["nkv"] in nars_usl_cancel:
#             nars_usl_cancel.remove(two["nkv"])
#     kol_lab = len(nars_lab_ok)
#     kol_usl = len(nars_usl_ok)
#     kol_all = kol_lab + kol_usl
#     opl2 = opl.split(",")
#     opl_new = []
#     for one in opl2:
#         opl_new.append(int(one))
#     try:
#         if Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).exists():
#             Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).update(
#                 kol_lab=kol_lab,
#                 kol_usl=kol_usl,
#                 kol_all=kol_all,
#                 stu_lab=stu_lab,
#                 stu_usl=stu_usl,
#                 stu_all=stu_all,
#                 nars_lab=nars_lab_ok,
#                 nars_usl=nars_usl_ok,
#                 nars_lab_cancel=nars_lab_cancel,
#                 nars_usl_cancel=nars_usl_cancel,
#             )
#         else:
#             Zav_report.objects.create(
#                 mpp=mpp,
#                 year=year,
#                 month=month,
#                 dn=dn,
#                 dk=dk,
#                 opl=opl,
#                 kol_lab=kol_lab,
#                 kol_usl=kol_usl,
#                 kol_all=kol_all,
#                 stu_lab=stu_lab,
#                 stu_usl=stu_usl,
#                 stu_all=stu_all,
#                 nars_lab=nars_lab_ok,
#                 nars_usl=nars_usl_ok,
#                 nars_lab_cancel=nars_lab_cancel,
#                 nars_usl_cancel=nars_usl_cancel,
#             )

#         for nar in nars_lab_cancel:
#             try:
#                 naryad = It_lab.objects.filter(nkv=nar).order_by("-id_etap").first()
#                 naryad.dzr = None
#                 naryad.dz_etap = None
#                 naryad.save()
#                 It_lab.objects.filter(nkv=nar).update(dzr=None, pdzr=None)
#                 It_lab.objects.filter(nkv=nar).order_by("-id_etap").first().update(dz_etap=None)
#                 db.write(f"update pl_uslk set dzr=null, status=2 where nkv='{nar}'")
#             except Exception as error:
#                 print(error)
#         for nar in nars_usl_cancel:
#             try:
#                 db.write(f"update pl_uslk set dzr=null, status=2 where nkv='{nar}'")
#             except Exception as error:
#                 print(error)
#         dn = datetime.datetime.strptime(dn, "%d.%m.%Y")
#         dn = dn.strftime("%Y-%m-%d")
#         dk = datetime.datetime.strptime(dk, "%d.%m.%Y")
#         dk = dk.strftime("%Y-%m-%d")
#         docs_finish = (
#             It_lab.objects.filter(id_etap=0, dzr__range=[dn, dk], sdl_set__doc=mpp, opl__opl__in=opl_new)
#             .select_related("patient")
#             .values("idkv", "nkv", "patient__fam", "patient__im", "patient__ot", "stu", "dou", "dzr", "sdl_set__doc")
#         )
#         docs_finish_list = list(docs_finish)
#         list_pd = []
#         list_pd.append("Фамилия доктора")
#         list_pd.append(mpp)
#         doc_finish_nar_pd_sum = 0
#         doc_finish_pd = []
#         for naryad in docs_finish_list:
#             doc_finish_nar_pd_sum += naryad["stu"]
#             doc_finish_pd.append(naryad)
#         list_pd.append(doc_finish_pd)
#         list_pd.append(len(doc_finish_pd))

#         if doc_finish_nar_pd_sum is None:
#             doc_finish_nar_pd_sum = 0
#         list_pd.append(doc_finish_nar_pd_sum)

#         select_pd = f"""select n_mpp.fam as doctorname, patient.fam, patient.im, patient.ot, pl_uslk.idkv, pl_uslk.nkv,
#         pl_uslk.dou, pl_uslk.dzr, pl_uslk.stu from pl_uslk, n_mpp, patient
#         where pl_uslk.vr=n_mpp.mpp
#         and pl_uslk.uid=patient.uid
#         and vr={mpp}
#         and pdog=0
#         and opl in ({opl})
#         and dzr>='{dn}'
#         and dzr<='{dk}'
#         and status in (2, 3)"""
#         pd_usl = db.sel_dict_in_list_desc(select_pd)
#         list_pd.append(pd_usl)

#         pd_sum_usl = 0
#         for usl in pd_usl:
#             pd_sum_usl += usl["STU"]
#         list_pd.append(pd_sum_usl)

#         # Добавляем периоды выборки для сверки на фронте
#         list_pd.append(dn)
#         list_pd.append(dk)

#         list_pd.append(opl)

#         return JsonResponse({"status": "ok", "list_nar": list_pd})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["POST"])
# def zav_report_control(request) -> JsonResponse:
#     # dn = request.POST["dn"]
#     # dk = request.POST["dk"]
#     opl = request.POST["opl"]
#     mpp = request.POST["mpp"]
#     year = request.POST["year"]
#     month = request.POST["month"]

#     try:
#         if Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).exists():
#             result = Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).values(
#                 "kol_lab", "kol_usl", "kol_all", "stu_lab", "stu_usl", "stu_all", "nars_lab", "nars_usl"
#             )
#             result = list(result)[0]
#             lab_nars_nkv = []
#             for nar in result["nars_lab"]:
#                 lab_nars_nkv.append(nar["nkv"])
#             usl_nars_nkv = []
#             for nar in result["nars_usl"]:
#                 usl_nars_nkv.append(nar["NKV"])
#             return JsonResponse(
#                 {
#                     "status": "ok",
#                     "kol_lab": result["kol_lab"],
#                     "kol_usl": result["kol_usl"],
#                     "kol_all": result["kol_all"],
#                     "stu_lab": result["stu_lab"],
#                     "stu_usl": result["stu_usl"],
#                     "stu_all": result["stu_all"],
#                     "nars_lab": result["nars_lab"],
#                     "nars_usl": result["nars_usl"],
#                     "lab_nars_nkv": lab_nars_nkv,
#                     "usl_nars_nkv": usl_nars_nkv,
#                 }
#             )
#         else:
#             return JsonResponse({"status": "not"})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["GET"])
# def once_nar_to_status5(request) -> JsonResponse:
#     dn = "26.07.2023"
#     dk = "25.08.2023"
#     # dn = "21.07.2023"
#     # dk = "20.08.2023"
#     # opl = request.POST["opl"]
#     date_start_pd = datetime.datetime.strptime(dn, "%d.%m.%Y")
#     date_end_pd = datetime.datetime.strptime(dk, "%d.%m.%Y")
#     date_end_pd
#     # naryads = It_lab.objects.filter(dzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3])
#     # naryads = It_lab.objects.filter(pdzr__range=[date_start_pd, date_end_pd], opl__opl=1, id_etap=0)
#     # naryads = It_lab.objects.filter(pdzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3], id_etap=0)
#     # count = 0
#     try:
#         # db.write(
#         #     f"update pl_uslk set status=5 where gr_otd=2 and opl in (3, 5, 10) and pdog=0 and dzr>='{dn}' and dzr<='{dk}'"
#         # )
#         #     for nar in naryads:
#         #         It_lab.objects.filter(nkv=nar.nkv).update(dzr=None, pdzr=nar.dzr)
#         #         if nar.nkv == 1082019:
#         #             continue
#         #         db.write(f"Update pl_uslk set status=5 where nkv={nar.nkv}")
#         #         count += 1
#         # return JsonResponse({"status": "ok"})
#         return JsonResponse({"status": "ok"})
#     except Exception as inst:
#         return JsonResponse({"status": "error", "message": inst})


# @require_http_methods(["GET"])
# def once_nar_to_status2(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(
#         id_etap=0, dzr__isnull=True, pdzr__isnull=False, check_zav=True, check_tech=False, opl__opl__in=[10, 5, 3]
#     )
#     nar_stu = 0
#     for nar in naryads:
#         nar_stu += nar.stu
#         It_lab.objects.filter(idkv=nar.idkv).update(dzr=nar.pdzr, check_tech=True)
#         db.write(f"update pl_uslk set status=2, dzr={nar.pdzr} where idkv='{nar.idkv}'")
#     select = "select * from pl_uslk where status=6 and pdog=0 and gr_otd=2 and opl in (10,5,3)"
#     result = db.sel_dict_in_list_lowerkeys(select)
#     usl_stu = 0
#     for res in result:
#         usl_stu += res["stu"]
#     try:
#         # db.write("update pl_uslk set status=2 where status=6 and pdog=0 and gr_otd=2 and opl in (10,5,3)")
#         db.write("update pl_uslk set status=2 where status=6 and pdog=1 and gr_otd=2 and opl in (10,5,3)")
#     except Exception as error_usl:
#         print(error_usl)

#     return JsonResponse({"status": "ok"})


# @require_http_methods(["GET"])
# def once_nar_to_status_6_2(request) -> JsonResponse:
#     # dn = "26.07.2023"
#     # dk = "25.08.2023"
#     # dn = "21.07.2023"
#     # dk = "21.08.2023"
#     # opl = request.POST["opl"]
#     # date_start_pd = datetime.datetime.strptime(dn, "%d.%m.%Y")
#     # date_end_pd = datetime.datetime.strptime(dk, "%d.%m.%Y")
#     naryads = It_lab.objects.filter(
#         dzr__isnull=True, pdzr__isnull=False, check_zav=True, check_tech=True, opl__opl__in=[10, 5, 3]
#     )
#     # naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=True, pdzr__isnull=False, sdl_set__tech=985)
#     nar_stu = 0
#     for nar in naryads:
#         naryad_time = nar.pdzr.strftime("%d.%m.%Y")
#         nar_stu += nar.stu
#         It_lab.objects.filter(idkv=nar.idkv).update(dzr=nar.pdzr, check_tech=True)
#         db.write(f"update pl_uslk set status=2, dzr='{naryad_time}' where idkv='{nar.idkv}'")
#     # select = "select * from pl_uslk where status=6 and pdog=0"
#     # result = db.sel_dict_in_list_lowerkeys(select)
#     # usl_stu = 0
#     # for res in result:
#     #     usl_stu += res["stu"]
#     # db.write("update pl_uslk set status=2 where status=6")
#     # naryads = It_lab.objects.filter(dzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3])
#     # naryads = It_lab.objects.filter(pdzr__range=[date_start_pd, date_end_pd], opl__opl=1, id_etap=0)
#     # naryads = It_lab.objects.filter(pdzr__range=[date_start_pd, date_end_pd], opl__opl__in=[10, 5, 3], id_etap=0)
#     # count = 0
#     # try:
#     # db.write(
#     #     f"update pl_uslk set status=5 where gr_otd=2 and opl in (3, 5, 10) and pdog=0 and dzr>='{dn}' and dzr<='{dk}'"
#     # )
#     #     for nar in naryads:
#     #         It_lab.objects.filter(nkv=nar.nkv).update(dzr=None, pdzr=nar.dzr)
#     #         if nar.nkv == 1082019:
#     #             continue
#     #         db.write(f"Update pl_uslk set status=5 where nkv={nar.nkv}")
#     #         count += 1
#     # return JsonResponse({"status": "ok"})
#     # return JsonResponse({"status": "ok"})
#     # except Exception as inst:
#     #     return JsonResponse({"status": "error", "message": inst})
#     return JsonResponse({"status": "ok"})


# @require_http_methods(["GET"])
# def once_nar_to_status2_check(request) -> JsonResponse:
#     naryads = It_lab.objects.filter(
#         id_etap=0, dzr__isnull=False, pdzr__isnull=False, check_zav=True, check_tech=True, opl__opl=1
#     )
#     nar_stu = 0
#     for nar in naryads:
#         result = db.sel_dict_in_list_lowerkeys(f"select nkv from pl_uslk where idkv={nar.idkv} and dzr is null")
#         if len(result) > 0:
#             nar_stu += nar.stu
#         # It_lab.objects.filter(idkv=nar.idkv).update(dzr=nar.pdzr, check_tech=True)
#         # db.write(f"update pl_uslk set status=2 where idkv='{nar.idkv}'")
#     # select = "select * from pl_uslk where status=6 and pdog=0"
#     # result = db.sel_dict_in_list_lowerkeys(select)
#     # usl_stu = 0
#     # for res in result:
#     #     usl_stu += res["stu"]
#     # db.write("update pl_uslk set status=2 where status=6")
#     return JsonResponse({"status": "ok"})


# @require_http_methods(["GET"])
# def check_nar_tech_by_mpp(request) -> JsonResponse:
#     mpp = 985
#     naryads = It_lab.objects.filter(
#         id_etap=0, dzr__isnull=False, pdzr__isnull=False, check_tech=True, check_zav=False, sdl_set__tech=mpp
#     )
#     # naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=True, sdl_set__tech=mpp)
#     # naryads = It_lab.objects.filter(id_etap=0, dzr__isnull=False, sdl_set__tech=985, check_zav=True, check_tech=True)
#     count = 0
#     stu = 0
#     for nar in naryads:
#         if nar.pdzr is not None:
#             It_lab.objects.filter(idkv=nar.idkv).update(check_zav=True)
#             count += 1
#             stu += nar.stu
#         # result = db.sel_dict_in_list_lowerkeys(f"select * from pl_uslb where idkv={nar.idkv} and sdl=35")
#         # if len(result) > 0:
#         #     count += 1
#         # else:
#         # pass
#     return JsonResponse({"status": "ok"})


# @require_http_methods(["GET"])
# def once_add_podr_to_zav(request) -> JsonResponse:
#     podr_list = [
#         {"lpu_name": "Березовское стоматологическое отделение", "lpu_number": 3},
#         {"lpu_name": "Яшкинское стоматологическое отделение", "lpu_number": 32},
#         {"lpu_name": "Поликлиника №5", "lpu_number": 245},
#         {"lpu_name": "Стоматологическое отделение", "lpu_number": 243},
#         {"lpu_name": "Поликлиника №4", "lpu_number": 236},
#         {"lpu_name": "Поликлиника №3", "lpu_number": 165},
#         {"lpu_name": "Поликлиника №2", "lpu_number": 164},
#         {"lpu_name": "Поликлиинка №1", "lpu_number": 162},
#         {"lpu_name": "Топкинское стоматологическое отделение", "lpu_number": 28},
#     ]
#     podr_list2 = [
#         {"lpu_name": "Поликлиника №3", "lpu_number": 165},
#     ]
#     # mpp = 346  # Ковалева
#     # mpp2 = 434  # Рахимов
#     # mpp = 918  # Шустов
#     # mpp = 111  # Яхно
#     zav = MyUser.objects.get(mpp=111)
#     # zav2 = MyUser.objects.get(mpp=434)
#     try:
#         Mpp_podr.objects.create(mpp=zav, podr=podr_list)
#         # Mpp_podr.objects.create(mpp=zav2, podr=podr_list2)
#     except Exception as error:
#         print(error)
#     # ready_podr = Mpp_podr.objects.get(mpp=zav)
#     # ready_podr2 = Mpp_podr.objects.get(mpp=zav2)
#     return JsonResponse({"status": "ok"})


# @require_http_methods(["GET"])
# def mpp_podr_list(request, mpp: int) -> JsonResponse:
#     user = MyUser.objects.filter(mpp=mpp).first()
#     mpp_podr = Mpp_podr.objects.filter(mpp=user).first()
#     list_podr = mpp_podr.podr
#     if user is not None and list_podr is not None:
#         return JsonResponse({"status": "ok", "list_podr": list_podr})
#     else:
#         return JsonResponse({"status": "error", "list_podr": [], "text": f"user: {user}, list_podr: {list_podr}"})


# @require_http_methods(["GET"])
# def images_view_by_nkv(request, nkv: int) -> JsonResponse:
#     image_list = Images.objects.filter(naryad=nkv).values_list("img", flat=True)
#     images_raw = list(image_list)
#     images: list[str] = []
#     for img in images_raw:
#         if "/2023/09/16/" in img or "/2023/09/17" in img or "/2023/09/18/" in img or "/2023/09/19/" in img:
#             images.append(f"http://192.168.100.48:8000/uploads/{img}")
#     return JsonResponse({"status": "ok", "count": len(images), "image_list": images})
#     # if user is not None and list_podr is not None:
#     #     return JsonResponse({"status": "ok", "list_podr": list_podr})
#     # else:
#     #     return JsonResponse({"status": "error", "list_podr": [], "text": f"user: {user}, list_podr: {list_podr}"})


# @require_http_methods(["GET"])
# def get_brigades(request, nkv: int) -> JsonResponse:
#     naryad = It_lab.objects.filter(id_etap=0, nkv=nkv).first()
#     mpp_tech: int = naryad.sdl_set.tech
#     mpp_lit: int = naryad.sdl_set.lit
#     mpp_pol: int = naryad.sdl_set.pol
#     mpp_cadcam: int = naryad.sdl_set.cadcam
#     name_tech: str = (MyUser.objects.get(mpp=mpp_tech)).get_full_name() if mpp_tech > 0 else ""
#     name_lit: str = (MyUser.objects.get(mpp=mpp_lit)).get_full_name() if mpp_lit > 0 else ""
#     name_pol: str = (MyUser.objects.get(mpp=mpp_pol)).get_full_name() if mpp_pol > 0 else ""
#     name_cadcam: str = (MyUser.objects.get(mpp=mpp_cadcam)).get_full_name() if mpp_cadcam > 0 else ""
#     dict_tech: dict[str, int | str] = {"mpp": mpp_tech, "name": name_tech}
#     dict_lit: dict[str, int | str] = {"mpp": mpp_lit, "name": name_lit}
#     dict_pol: dict[str, int | str] = {"mpp": mpp_pol, "name": name_pol}
#     dict_cadcam: dict[str, int | str] = {"mpp": mpp_cadcam, "name": name_cadcam}
#     result_dict: dict[str, dict] = {"tech": dict_tech, "lit": dict_lit, "pol": dict_pol, "cadcam": dict_cadcam}
#     return JsonResponse({"status": "ok", "brigade": result_dict})


# @require_http_methods(["GET"])
# def get_list_spec(
#     request,
# ) -> JsonResponse:
#     list_tech = User_sdl.objects.filter(sdls__sdl=35)
#     list_tech_done: list[str, int | str] = [
#         {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_tech
#     ]
#     list_lit = User_sdl.objects.filter(sdls__sdl=37)
#     list_lit_done: list[str, int | str] = [{"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_lit]
#     list_pol = User_sdl.objects.filter(sdls__sdl=36)
#     list_pol_done: list[str, int | str] = [{"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_pol]
#     list_cadcam = User_sdl.objects.filter(sdls__sdl=38)
#     list_cadcam_done: list[str, int | str] = [
#         {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_cadcam
#     ]
#     dict_brigade: dict[str, list] = {
#         "tech": list_tech_done,
#         "lit": list_lit_done,
#         "pol": list_pol_done,
#         "cadcam": list_cadcam_done,
#     }
#     return JsonResponse({"status": "ok", "brigade": dict_brigade})


# @require_http_methods(["GET"])
# def finish_nar_by_st(request, nkv: int, lab: int = 0) -> JsonResponse:
#     naryad = It_lab.objects.filter(nkv=nkv, id_etap=0).first()
#     try:
#         if lab == 0:
#             It_lab.objects.filter(nkv=nkv).update(check_tech=True, dzr=naryad.pdzr)
#         db.write(f"update pl_uslk set status=2 where nkv={nkv}")
#     except Exception as errorstr:
#         print(errorstr)
#         return JsonResponse({"status": "error", "message": errorstr})
#     return JsonResponse({"status": "ok", "message": "Успешно записано"})


# @require_http_methods(["GET"])
# def get_brigade_arena(request, nkv: int) -> JsonResponse:
#     naryad = It_lab.objects.filter(nkv=nkv, id_etap=0).first()
#     dict_result: dict[str, int] = {"tech": 0, "lit": 0, "pol": 0, "cadcam": 0}
#     try:
#         result = db.sel_dict_in_list_lowerkeys(f"select * from pl_uslb where idkv={naryad.idkv}")
#         for one in result:
#             if one["sdl"] == 35:
#                 dict_result["tech"] = one["mpp"]
#             if one["sdl"] == 37:
#                 dict_result["lit"] = one["mpp"]
#             if one["sdl"] == 36:
#                 dict_result["pol"] = one["mpp"]
#             if one["sdl"] == 38:
#                 dict_result["cadcam"] = one["mpp"]
#     except Exception as errorstr:
#         print(errorstr)
#         return JsonResponse({"status": "error", "message": errorstr})
#     return JsonResponse({"status": "ok", "brigade": dict_result})


# def get_sum_by_mpp_zam(request, nkv: int) -> JsonResponse:
#     naryad = It_lab.objects.filter(nkv=nkv, id_etap=0).first()
#     dict_result: dict[str, int] = {"tech": 0, "lit": 0, "pol": 0, "cadcam": 0}
#     try:
#         result = db.sel_dict_in_list_lowerkeys(f"select * from pl_uslb where idkv={naryad.idkv}")
#         for one in result:
#             if one["sdl"] == 35:
#                 dict_result["tech"] = one["mpp"]
#             if one["sdl"] == 37:
#                 dict_result["lit"] = one["mpp"]
#             if one["sdl"] == 36:
#                 dict_result["pol"] = one["mpp"]
#             if one["sdl"] == 38:
#                 dict_result["cadcam"] = one["mpp"]
#     except Exception as errorstr:
#         print(errorstr)
#         return JsonResponse({"status": "error", "message": errorstr})
#     return JsonResponse({"status": "ok", "brigade": dict_result})
